semi-newbie module namespace confusion

David Murmann david.murmann at rwth-aachen.de
Tue Oct 4 05:10:18 EDT 2005


Fredrik Lundh wrote:
> David Murmann wrote:
> 
>> I ran into the same problem some time ago and even wanted to post here
>> about it, but found out that it had been reported as a bug three times
>> at sourceforge (if i remember correctly). The comments there explained
>> it of course, but I still think that this behavior is somehow "wrong".
>>
>> I like to think of the import statement as a way to provide the names
>> defined in a module to the current namespace, so there is no "this gets
>> evaluated twice".
> 
> are you sure you understand the problem?  import does exactly what you
> say; it creates a module object and populates it by running the code in the
> module.
maybe i don't... but i'm not convinced yet, see below.

> the problem is that when you hand Python a chunk of code (a script), it
> doesn't necessarily know where it came from.  and even if you know the
> filename it came from, there's no way to know if that chunk actually corre-
> sponds to a module somewhere out there (the import system can map a
> module name to a file, but it cannot map a file to a module name).
well, in my opinion python is not trying hard enough. to me it is
immediately obvious that the main module gets evaluated twice and
i am rather sure that one could introduce some magic of the kind
"oh, i reevaluate the main script here, the module does not get filled
the usual way but uses the existing objects instead". this would have
to happen on a very low level (when the file i just read from is known)
but i think it would be possible. whether the effort to do so is worth
it, is a different question...

>> Now i wonder how difficult it would be to "correct" the behavior?
> 
> there's no way to "fix" it without introducing a huge number of inconsistencies.
> 
>> And would such a change break any code?
> 
> any code that uses the "if __name__ == "__main__" pydiom, for a start.
i wouldn't lose that, the main module should still be named "__main__",
it should just get more names (somehow) :)
i see, it's difficult at the moment

hoping i'm not completely wrong here, David.



More information about the Python-list mailing list