This question already has answers here:
Python: How can I run eval() in the local scope of a function
(2 answers)
Closed 3 years ago.
My code is similar like this:
class NN(object):
def __init__(self,config=None,opts=None):
self.file_vars = ['self.corpusfile','self.dbfile']
self.corpusfile="data.json"
self.dbfile="db.json"
def saveNet(self):
for name in self.file_vars:
print(name)
print(eval(name))
b=dict( [(name,eval(name)) for name in self.file_vars])
a=NN()
a.saveNet()
the result is :
self.corpusfile
data.json
self.dbfile
db.json
error message is:
NameError: name 'self' is not defined
how to solve this problem?
The list comprehension has its own local variable scope. eval can't see self, because self comes from an outer scope, and nothing triggers the closure variable mechanism that would be necessary for eval to see the variable. (The self reference in self.file_vars doesn't trigger it, because that expression is evaluated outside the list comprehension's scope, despite being part of the list comprehension.)
Stop using eval. It's dangerous, almost always a bad idea, and completely unnecessary for something like this. Appropriate replacement tools might include getattr, self.__dict__, or something else, depending on what your full use case looks like.
Related
This question already has answers here:
How to create dynamical scoped variables in Python?
(4 answers)
Closed 2 years ago.
Why, in this code, can't I access db or file from inside do_more()?
def do_stuff(queue):
db = getDbConn()
while True:
file = queue.get() #DirEntry object
...
do_more(otherObject)
q.task_done()
I'm aware I could pass db and file as arguments to do_more(), but I feel like those variables should just be available in functions called from other functions. It works that way from main to first level functions. What am I missing here?
In the code you provided, you don't even attempt using the variables from do_stuff.
But as a general rule, you should be able to use variables from a parent function inside a child function, either by passing them as variables or by using them when initializing the child function, like this:
def foo():
foo2 = "foo"
def bar():
print(foo2)
bar()
foo()
If i did not answer your question let me know.
no , you cant access those variables , I know what you think , which is wrong.
you can access variables inside loops and if statements, not here.
imagine you have a function which is used in many different places, in that case you have access from this function to many variables which makes things complicated.
functions should be stand-alone objects which take some arguments do stuff and return something.so inside a function scope you can only see variables which are defined there and the arguments passed from the parent function using parenthesis.
This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 3 years ago.
def convert(target):
#Some code here
target = 20
convert(x)
print(x)
I expected the output to be 20, but there is always an error. "NameError: Name x is not defined" Is there some way that I could fix that?
It sounds like you are trying to pass the value by reference, which goes against the grain of Python, which passes variable by assignment. The easiest "solution" is to refactor your code so it returns the new value, as others have suggested.
In some languages (e.g. PHP), you can specify that certain arguments are to be passed by reference (e.g. by prefixing the variable name with a "&"), but in practice this often makes the code harder to read and debug.
For more information, see:
How do I pass a variable by reference?
This question already has answers here:
Can you explain closures (as they relate to Python)?
(13 answers)
Closed 6 years ago.
Let's suppose to have this simple code:
def my_outer_function():
outer_var = 123
def my_inner_function():
return outer_var + 1
return my_inner_function
get_inner = my_outer_function()
get_inner()
I wonder there isn't any kind of runtime error. outer_var - the variable of the outer function - is available only when that function is running on, i.e. it vanishes when my_outer_function ends. But when I call get_inner(), my_outer_function() is already ended so I would have bet on a runtime error since my_inner_function couldn't find outer_var.
How do you explain all this?
the variable of the outer function is available only when that function is running on, i.e. it vanishes when my_outer_function ends.
That's not entirely true. The variable is available in my_outer_function's scope. my_inner_function has the scope of its own declarations and its parent's scope.
my_inner_function references a variable outside of its own scope, and so those references are bound to my_inner_function as a closure when its parent's scope is no longer available. To learn more about closures, see Can you explain closures (as they relate to Python)? (taken from Paul Rooney's comment)
This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 5 months ago.
I'm a Python beginner and I am from C/C++ background. I'm using Python 2.7.
I read this article: A Beginner’s Guide to Python’s Namespaces, Scope Resolution, and the LEGB Rule, and I think I have some understanding of Python's these technologies.
Today I realized that I can write Python code like this:
if condition_1:
var_x = some_value
else:
var_x = another_value
print var_x
That is, var_x is still accessible even it is not define before the if. Because I am from C/C++ background, this is something new to me, as in C/C++, var_x are defined in the scope enclosed by if and else, therefore you cannot access it any more unless you define var_x before if.
I've tried to search the answers on Google but because I'm still new to Python, I don't even know where to start and what keywords I should use.
My guess is that, in Python, if does not create new scope. All the variables that are newly defined in if are just in the scope that if resides in and this is why the variable is still accessible after the if. However, if var_x, in the example above, is only defined in if but not in else, a warning will be issued to say that the print var_x may reference to a variable that may not be defined.
I have some confidence in my own understanding. However, could somebody help correct me if I'm wrong somewhere, or give me a link of the document that discusses about this??
Thanks.
My guess is that, in Python, if does not create new scope. All the variables that are newly defined in if are just in the scope that if resides in and this is why the variable is still accessible after the if.
That is correct. In Python, namespaces, that essentially decide about the variable scopes, are only created for modules, and functions (including methods; basically any def). So everything that happens within a function (and not in a sub-function) is placed in the same namespace.
It’s important to know however that the mere existance of an assignment within a function will reserve a name in the local namespace. This makes for some interesting situations:
def outer ():
x = 5
def inner ():
print(x)
# x = 10
inner()
outer()
In the code above, with that line commented out, the code will print 5 as you may expect. That’s because inner will look in the outer scope for the name x. If you add the line x = 10 though, the name x will be local to inner, so the earlier look up to x will look in the local namespace of inner. But since it hasn’t been assigned yet, you will receive an UnboundLocalError (“local variable 'x' referenced before assignment”). The nonlocal statement was added in Python 3 to overcome one issue from this: The situation where you want to actually modify the x of the outer scope within the inner function.
For more information on name lookup, see this related question.
This question already has answers here:
How do I check if a variable exists?
(14 answers)
Closed 9 years ago.
While working with many if/elif/else I sometime loose a track if a variable has been already declared. I would like to know a simple way to check if the variable foo has been already declared. What would be the simplest syntax to accomplish that?
P.s. It was interesting to see how globals() and locals() could be used to accomplish this.
EDIT:
I've ended up using:
if not 'myVariableName' in globals().keys(): myVariableName='someValue'
It's hard to track when and where/if app = QtGui.QApplication(sys.argv) had been already declared especially in situation when one gui module calls another and vise versa.
if 'app' in globals() (seems) helps to avoid an accidental variable re-declaration.
try:
foo
except NameError:
# does not exist
else:
# does exist
Rather than worrying about if a variable is declared, declare all variables from the start. You can give variables some value to indicate that it is still in a initial state, such as
foo = None
or, if you want to use None for some other purpose, you can create a unique value to indicate the initial state, such as
INITIAL = object()
foo = INITIAL
Later, if you need to check if the variable has been set, you could just use if:
if foo == INITIAL:
I think the main advantages to doing it this way are
You'll never accidentally raise a NameError.
There will be one place in your code where all the variables are
introduced, so readers of your code do not have to wonder what
variables are in play.
By the way, it is similarly a good idea to define all instance attributes in __init__, so there is no question about what attributes an instance may have.