Python: default variable in definition not defined when importing module
Python: default variable in definition not defined when importing module
Let's say I have a module foo.py
that contains the following function:
foo.py
def bar(var=somedict):
print(var)
In my main program, main.py
, I import this module, define the variable somedict
and then run the function bar
:
main.py
somedict
bar
from foo import *
somedict = 'foobar'
bar()
The idea is that somedict
is passed along as default parameter without having to specify it explictly (which I'd like to avoid for the actual program I'm writing).
somedict
However, Python throws a NameError: name 'somedict' is not defined
. How can I still import the module and have the desired 'passing along of the default variable'? Thanks!
NameError: name 'somedict' is not defined
1 Answer
1
somedict
is not defined during import. So from foo import *
throws the error NameError: name 'somedict' is not defined
somedict
from foo import *
NameError: name 'somedict' is not defined
So modify foo.py
as follows
foo.py
somedict=
def bar(var=None):
if var is None:
var=somedict
print(var)
Now, you should be able to do what were trying, in a slightly different form
import foo
foo.somedict = 'a':1
foo.bar()
main.py
from foo import *
somedict
foo
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks, that solved the problem! If I may ask, as a follow-up: is this also possible when the
main.py
script uses a star import, i.e.from foo import *
? And if so, how would you then changesomedict
inside thefoo
module? That would make the code even simpler for the end user.– DaanMusic
Aug 26 at 10:40