sending a variable to an imported module

Dave Angel d at davea.name
Thu Dec 8 07:15:26 EST 2011


On 12/08/2011 06:28 AM, Bastien Semene wrote:
> Hi list,
>
> I'm trying to pass a variable to an imported module without singletons.
> I've seen in the doc, and tested that I can't use global to do it :
>
> === module.py ===
> def testf():
>  print test
>
>
> === main.py ===
> global test
> test = 1
>
> imported_module = __import__(module, globals(), locals(), [], -1)
>
> importmodule.testf()
>
> === output ===
> NameError: global name 'test' is not defined
>
>
Please paste your code and your stacktrace, don't retype them.  In the 
above, you spelled 'imported_module" two different ways, and forgot the 
quotes around "modue", so it couldn't run.  There are probably other 
problems, but what's the point?
>
> While I was reading many (many) threads about singleton I read people 
> claiming that singletons can always be avoided (I can't remeber the 
> most relevant thread on stackoverflow).
> I don't want to start a new debate about singletons, I think Internet 
> has enough debates yet.
>
> But in my case I'd like to access this variable anywhere and at 
> anytime without having to pass it as a parameter everywhere (this 
> variable is a configuration manager object).
> How can I achieve that without singletons ?
> I'm beginner in Python, that's why I'm maybe missing something obvious.
global variables are global only within their own module, but you 
probably knew that.

And using the global keyword in main.py isn't accomplishing anything.  
Since you're not inside a def or a class, test is already global, as 
soon as you give it a value.

You don't pass values to a module, you load the module.  And if the 
module doesn't have any top-level code, you can "monkey-patch" it to 
your heart's content, on lines following.

If mymodule.py doesn't have a global value test, and you wish it did, 
you can simply do something like:
import  mymodule
mymodule.test = 42
This attribute of mymodule is totally unrelated to one of the same name 
in main.py.  if you want to refer to it, or to change it again, from 
main.py, you'd have to use  mymodule.test.

If the module had top-level code that needed to see your new global, 
then you'd have a problem, because you can't put it there till after the 
import returns.

Now, most of the time when this sort of thing happens, what you really 
want is to define another module whose only purpose is to supply these 
common values.  That module should get imported by both your script and 
your module.


-- 

DaveA




More information about the Python-list mailing list