python - return function -- get variable name - python-2.7

I was wondering if it is possible to use the return function and get the variable name
p.s ^ help to rephrase the above line
If you do not understand, here is the code:
def foo():
return <get variable name here>
a = foo()
Therefore, it will return 'a' to the variable a, 'b' to the variable b and so on, which means
the variable will contain its name.
Is there a function to return the variable's name ?

Can you write what you need that for?
There is no way to do that as you wish. But you can:
- do that without return, just define variable outside the function
- return a dict like {'a': variable}
There are other possibilities, depends only what are you want to do.

IMPORTANT: this is ugly and is probably WRONG way to do what you wanna do. Show us the whole use case, so we'll be able to help you choose better solution.
It is almost possible. Lets consider this:
g = True
def foo(val):
a = 5
b = "abc"
return XXX
And you want XXX to be "g" when val is True, "a" if val is 5 and "b" when val is "abc". You can inspect local and global variables with locals() and globals():
g = True
def foo(val):
a = 5
b = "abc"
for k, v in locals().iteritems(): # this will iterate over {"a": 5, "b": "abc"}
if v == var: # or "is" if you want identity
return k
for k, v in globals().iteritems(): # this will iterate over {"g": True, "foo": <this function>}
if v == var: # or "is" if you want identity
return k
return <default value>
Of course, there may be many names with the same value, and random of that names will be returned, if any. For example, it both a and b would have value 5 and you pass 5 as val, there is no way to tell which of them will be returned.
I REPEAT. WHATEVER YOU'RE TRYING TO DO, THIS IS WRONG (WITH 99.999% PROBABILITY). THERE ARE SOME REALLY SPECIAL SITUATIONS, WHEN locals() AND globals() MAY COME HANDY, BUT I DON'T THINK THIS IS ONE OF THOSE SITUATIONS.
== EDIT ==
I finally understood that you want to get the name of variable you're binding. Probably some tampering with stack trace could help you, but again - this is WRONG.

Related

Is there a way I can reduce this in-a-row kind of repeating Lua conditions?

I think I already could know the answer... but just to be totally sure, sometimes I find myself writing conditionals like:
if type(value) ~= "function" and type(value) ~= "table" and type(value) ~= "thread" and type(value) ~= "userdata" then
--do whatever...
end
And every time I wonder if there couldn't be a more economical way to do it, for example, like:
if type(value) ~= "function" and ~= "table" and ~= "thread" and ~= "userdata" then
--do whatever...
end
I mean, not having to repeat the whole individual condition all the times since the first part (type(value)) is always going to the same. Of course the above wouldn't work, but could it be any other way I'm simply not seeing? I hope it makes sense...
I do it like this. Coming from R, I am used to having the %in% function. Below, I create a function that works in a similar way in lua:
-- return true if one of the elements of tab is equal to el
local function in_tab(el, tab)
for _, v in pairs(tab) do
if el == v then return true end
end
return false
end
And you can call it like this:
if not in_tab(type(object),
{ "table", "userdata", "thread", "function" }) then ...
end
Given how fast pairs() is, this does not seem to incur any penalty on the computation time. In addition, it comes in very handy all the time.
Of course, if you keep testing against the same values, a much simpler solution is a simple lookup:
local dts = { table = true, userdata = true, thread = true }
if dts[ type(object) ] then ... end
Of course, in case of function you would have to do this:
dts["function"] = true
because neither { function = true } nor dts.function = true are allowed.
Why not create a function that mimics isinstance from Python?
local function isinstance(obj, ...)
local obj_type = type(obj)
for _, v in pairs{...} do
if v == obj_type:
return true
return false
end
Usage:
if not isinstance(value, "function", "table", "thread", "userdata") then
-- do whatever...
end
You may even want to add additional functionality like matching the "type" based on the metatable or disambiguating integers and floats.

Use value to another function in any function

def anshu():
a=1+2
print(a)
anshu()
def sanju():
b=2+3
print(b)
sanju()
def bala():
c=a+b
print(c)
can you explain?
I gave many value in one or more function i want use these value in any function in python
To access a variable from one function in another function, you can either return the variable from the first function and pass it as an argument to the second function, or you can make the variable global so that it can be accessed from any function. Here's an example using the first approach:
def anshu():
a = 1 + 2
return a
def sanju():
b = 2 + 3
return b
def bala(a, b):
c = a + b
print(c)
anshu_result = anshu()
sanju_result = sanju()
bala(anshu_result, sanju_result)
Here's an example using the second approach:
def anshu():
global a
a = 1 + 2
def sanju():
global b
b = 2 + 3
def bala():
c = a + b
print(c)
anshu()
sanju()
bala()
Note that using global variables is generally not considered good practice, because it can make your code difficult to maintain and debug. It's usually better to use the first approach of passing variables as arguments to functions.

Is List in Scala mutable or immutable? [duplicate]

What is the difference between a var and val definition in Scala and why does the language need both? Why would you choose a val over a var and vice versa?
As so many others have said, the object assigned to a val cannot be replaced, and the object assigned to a var can. However, said object can have its internal state modified. For example:
class A(n: Int) {
var value = n
}
class B(n: Int) {
val value = new A(n)
}
object Test {
def main(args: Array[String]) {
val x = new B(5)
x = new B(6) // Doesn't work, because I can't replace the object created on the line above with this new one.
x.value = new A(6) // Doesn't work, because I can't replace the object assigned to B.value for a new one.
x.value.value = 6 // Works, because A.value can receive a new object.
}
}
So, even though we can't change the object assigned to x, we could change the state of that object. At the root of it, however, there was a var.
Now, immutability is a good thing for many reasons. First, if an object doesn't change internal state, you don't have to worry if some other part of your code is changing it. For example:
x = new B(0)
f(x)
if (x.value.value == 0)
println("f didn't do anything to x")
else
println("f did something to x")
This becomes particularly important with multithreaded systems. In a multithreaded system, the following can happen:
x = new B(1)
f(x)
if (x.value.value == 1) {
print(x.value.value) // Can be different than 1!
}
If you use val exclusively, and only use immutable data structures (that is, avoid arrays, everything in scala.collection.mutable, etc.), you can rest assured this won't happen. That is, unless there's some code, perhaps even a framework, doing reflection tricks -- reflection can change "immutable" values, unfortunately.
That's one reason, but there is another reason for it. When you use var, you can be tempted into reusing the same var for multiple purposes. This has some problems:
It will be more difficult for people reading the code to know what is the value of a variable in a certain part of the code.
You may forget to re-initialize the variable in some code path, and end up passing wrong values downstream in the code.
Simply put, using val is safer and leads to more readable code.
We can, then, go the other direction. If val is that better, why have var at all? Well, some languages did take that route, but there are situations in which mutability improves performance, a lot.
For example, take an immutable Queue. When you either enqueue or dequeue things in it, you get a new Queue object. How then, would you go about processing all items in it?
I'll go through that with an example. Let's say you have a queue of digits, and you want to compose a number out of them. For example, if I have a queue with 2, 1, 3, in that order, I want to get back the number 213. Let's first solve it with a mutable.Queue:
def toNum(q: scala.collection.mutable.Queue[Int]) = {
var num = 0
while (!q.isEmpty) {
num *= 10
num += q.dequeue
}
num
}
This code is fast and easy to understand. Its main drawback is that the queue that is passed is modified by toNum, so you have to make a copy of it beforehand. That's the kind of object management that immutability makes you free from.
Now, let's covert it to an immutable.Queue:
def toNum(q: scala.collection.immutable.Queue[Int]) = {
def recurse(qr: scala.collection.immutable.Queue[Int], num: Int): Int = {
if (qr.isEmpty)
num
else {
val (digit, newQ) = qr.dequeue
recurse(newQ, num * 10 + digit)
}
}
recurse(q, 0)
}
Because I can't reuse some variable to keep track of my num, like in the previous example, I need to resort to recursion. In this case, it is a tail-recursion, which has pretty good performance. But that is not always the case: sometimes there is just no good (readable, simple) tail recursion solution.
Note, however, that I can rewrite that code to use an immutable.Queue and a var at the same time! For example:
def toNum(q: scala.collection.immutable.Queue[Int]) = {
var qr = q
var num = 0
while (!qr.isEmpty) {
val (digit, newQ) = qr.dequeue
num *= 10
num += digit
qr = newQ
}
num
}
This code is still efficient, does not require recursion, and you don't need to worry whether you have to make a copy of your queue or not before calling toNum. Naturally, I avoided reusing variables for other purposes, and no code outside this function sees them, so I don't need to worry about their values changing from one line to the next -- except when I explicitly do so.
Scala opted to let the programmer do that, if the programmer deemed it to be the best solution. Other languages have chosen to make such code difficult. The price Scala (and any language with widespread mutability) pays is that the compiler doesn't have as much leeway in optimizing the code as it could otherwise. Java's answer to that is optimizing the code based on the run-time profile. We could go on and on about pros and cons to each side.
Personally, I think Scala strikes the right balance, for now. It is not perfect, by far. I think both Clojure and Haskell have very interesting notions not adopted by Scala, but Scala has its own strengths as well. We'll see what comes up on the future.
val is final, that is, cannot be set. Think final in java.
In simple terms:
var = variable
val = variable + final
val means immutable and var means mutable.
Full discussion.
The difference is that a var can be re-assigned to whereas a val cannot. The mutability, or otherwise of whatever is actually assigned, is a side issue:
import collection.immutable
import collection.mutable
var m = immutable.Set("London", "Paris")
m = immutable.Set("New York") //Reassignment - I have change the "value" at m.
Whereas:
val n = immutable.Set("London", "Paris")
n = immutable.Set("New York") //Will not compile as n is a val.
And hence:
val n = mutable.Set("London", "Paris")
n = mutable.Set("New York") //Will not compile, even though the type of n is mutable.
If you are building a data structure and all of its fields are vals, then that data structure is therefore immutable, as its state cannot change.
Thinking in terms of C++,
val x: T
is analogous to constant pointer to non-constant data
T* const x;
while
var x: T
is analogous to non-constant pointer to non-constant data
T* x;
Favoring val over var increases immutability of the codebase which can facilitate its correctness, concurrency and understandability.
To understand the meaning of having a constant pointer to non-constant data consider the following Scala snippet:
val m = scala.collection.mutable.Map(1 -> "picard")
m // res0: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard)
Here the "pointer" val m is constant so we cannot re-assign it to point to something else like so
m = n // error: reassignment to val
however we can indeed change the non-constant data itself that m points to like so
m.put(2, "worf")
m // res1: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard, 2 -> worf)
"val means immutable and var means mutable."
To paraphrase, "val means value and var means variable".
A distinction that happens to be extremely important in computing (because those two concepts define the very essence of what programming is all about), and that OO has managed to blur almost completely, because in OO, the only axiom is that "everything is an object". And that as a consequence, lots of programmers these days tend not to understand/appreciate/recognize, because they have been brainwashed into "thinking the OO way" exclusively. Often leading to variable/mutable objects being used like everywhere, when value/immutable objects might/would often have been better.
val means immutable and var means mutable
you can think val as java programming language final key world or c++ language const key world。
Val means its final, cannot be reassigned
Whereas, Var can be reassigned later.
It's as simple as it name.
var means it can vary
val means invariable
Val - values are typed storage constants. Once created its value cant be re-assigned. a new value can be defined with keyword val.
eg. val x: Int = 5
Here type is optional as scala can infer it from the assigned value.
Var - variables are typed storage units which can be assigned values again as long as memory space is reserved.
eg. var x: Int = 5
Data stored in both the storage units are automatically de-allocated by JVM once these are no longer needed.
In scala values are preferred over variables due to stability these brings to the code particularly in concurrent and multithreaded code.
Though many have already answered the difference between Val and var.
But one point to notice is that val is not exactly like final keyword.
We can change the value of val using recursion but we can never change value of final. Final is more constant than Val.
def factorial(num: Int): Int = {
if(num == 0) 1
else factorial(num - 1) * num
}
Method parameters are by default val and at every call value is being changed.
In terms of javascript , it same as
val -> const
var -> var

How to search by member accessor value with std::find_if()?

I am learning C++ at the moment and have an example program implemented with an array of objects data store. To make some other operations easier, I have changed the store to a vector. With this change I am now not sure of the best way to search the store to find an object based on a member accessor value.
Initially I used a simple loop:
vector<Composer> composers; // where Composer has a member function get_last_name() that returns a string
Composer& Database::get_composer(string last_name)
{
for (Composer& c : composers)
if (c.get_last_name().compare(last_name))
return c;
throw std::out_of_range("Composer not found");
}
This works just fine of course, but to experiment I wanted to see if there were vector specific functions that could also do the job. So far I have settled on trying to use find_if() (if there is a better function, please suggest).
However, I am not sure exactly the correct way to use find_if(). Based on code seen in online research I have replaced the above with the following:
vector<Composer> composers; // where Composer has a member function get_last_name() that returns a string
Composer& Database::get_composer(string last_name)
{
auto found = find_if(composers.begin(), composers.end(),
[last_name](Composer& c) -> bool {c.get_last_name().compare(last_name);});
if (found == composers.end())
throw out_of_range("Composer not found");
else
return *found;
}
This does not work. It does find a result, but it is the incorrect one. If an argument that matches, say the third composer's last name the function always returns the first item from the vector (if I pass an argument that doesn't match any last name the function correctly throws an exception)... what am I doing wrong?
You are on the right track, your lambda needs return statement. Also in such case you do not have to specify it's return type explicitly, it can be deduced:
find_if(composers.begin(), composers.end(),
[last_name](const Composer& c) { return c.get_last_name() == last_name);});
you original code should not compile or at least emit warning(s), you should pay attention to them.
Note: it is not clear how your original code worked if you tested it, it should be:
if (c.get_last_name().compare(last_name) == 0 )
or simply:
if (c.get_last_name() == last_name )
as std::string::compare() returns int -1 0 or 1, so your code searches for string that does not match variable last_name
With range-v3, you may use projection:
auto it = ranges::find(composers, last_name, &composers::get_last_name);

How to return void in a function in OCaml?

Simple example: I have some functions and I need to call them all, to modify a structure, only in one function. With these simple functions the task can be made in ways that don't use void, but in others tasks you have to use void. So what can you do?
type player = { mutable name : string; mutable points : int } ;;
let putname brad = match brad with
{ name = x; points = y } -> { name = brad; points = y } ;;
let putpoint guy score = match guy with
{ name = x; points = y } -> { name = x; points = score } ;;
let loosers listplayer guy = guy :: listplayer ;;
Here is the problem - How can I do the next function?
let someoneloses guy = void
guy = putpoint guy 0 ;;
listplayer = loosers (listplayer guy) ;;
Given you are using the name "void" I'm assuming you are more familiar with C (or C++). In OCaml the equivalent of "void" (the name of the type for no value) is "unit". There is another difference though: while in C the syntax is complex enough that it have constructs for no values (for instance, you can either "return a_value;" or "return;", two differents yet syntactically valid use cases for the keyword "return"), in OCaml the syntax is simpler and always require a value. So we have a notation for "nothing", which is, astutely but maybe also confusedly, is written "()".
So, the OCaml equivalent of the C:
void do_nothing(void) { return; }
is written:
let do_nothing () = ()
(notice how OCaml syntax is simpler and easier to grok once you got the "()" trick).
Now that this is hopefully clearer, back to your question.
A function that returns nothing is a function that return "()", either explicitly (as "do_nothing" above) or because it ends with an expression that has "()" as its value. For instance, an assignment (something tell me you'll love assignments), such as:
let putpoint guy score = guy.points <- score
Now back to your problem. You seem to be doing some kind of game with players represented as mutable records and some functions modifying those records as the game develop. You need not use pattern matching for that. Actually, functions such as "putpoint" above is probably what you want. But then you need some more state in your program: the list of loosers for instance is probably going to be a reference to a list that you modify etc.
This is the "imperative" side of OCaml but there is another one, which is usually regarded as more elegant although often slower in general (but not in functional languages which are optimised for this technique), consisting of refraining from altering state (changing values of things) but instead using functions merely taking values and returning values. Implemented like this, a player would be represented as an immutable record and each function acting a user would take an "old user" and return a "new user", and the same goes with the list of loosers, and so on. Actually, the whole game state would be represented as a big value that the "main loop" of your program would, given the previous value, and possible also the time and user inputs, would compute the "new state" and return it.
Have fun!
Also, your question has nothing to do with ocaml-batteries.
since you are using mutable data, you just have to assigned the value directly.
let p = {name = "me";points=0};;
let update x = x.name <- "you";
x.points <- 3;;
update p ;;