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()





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 change somedict inside the foo module? That would make the code even simpler for the end user.
– DaanMusic
Aug 26 at 10:40


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)