Why do directly imported variables behave differently than those attached to imported module?

Chris Rebert clp2 at rebertia.com
Tue May 3 18:11:48 EDT 2011


On Tue, May 3, 2011 at 2:47 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, May 4, 2011 at 2:57 AM, Chris Rebert <clp2 at rebertia.com> wrote:
>> from foo import *
>>
>> can be thought of as essentially doing:
>>
>> import foo
>> set = foo.set
>> var = foo.var
>> del foo
>
> Here's a side point. What types will hold a reference to the enclosing
> module (or at least its dictionary)? Would it be possible to use a
> from import to load a module, then "lose" the module even though
> you're using objects from it?
>
> I am guessing that a function or class will hold such a reference,
> because otherwise it would be a bit awkward for them to use any sort
> of module-level state. Or do they not, and instead go look for their
> module in sys.modules?

some_python_function.__globals__ is the exact reference you postulated.
Classes don't seem to hold such references; their methods do though
(by virtue of being function objects), which makes sense.

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list