[Python-3000] PEP to change how the main module is delineated

Nick Coghlan ncoghlan at gmail.com
Mon Apr 23 23:22:00 CEST 2007


Brett Cannon wrote:
> On 4/23/07, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> Then the import machinery was modified such that if it came across an
>> explicit relative import being made from a module called "__main__", it
>> would check to see if "__module_name__" was set, and if so, use that
>> instead.
>>
> 
> I don't like having to tweak the import machinery for this.  It feels
> like working around a problem instead of trying to solve it.

As you yourself said, it's a relative import problem, more so than a 
main module execution problem. I think addressing it on the import side 
(with some cooperation from the main module execution code) reflects that.

The other nice thing about this solution, is that you can explicitly 
enable main relative imports without using "-m", simply by setting 
__module_name__ appropriately (an alternative would be to call the 
additional attribute __package_name__, to save a small amount of string 
fiddling in the relative import code)

>  Plus it
> doesn't address Steve's concerns of when modules are still named
> '__main__' because there absolute name cannot be figured out.

That problem is never going to go away, IMO - if you run a file 
directly, Python has no clue where in the package hierarchy you intend 
it to live. We provide a mechanism (the -m switch) that allows people to 
be explicit if they want to - other than that, I say we resist the 
temptation to guess (take a look at PEP 302 to get some idea of just how 
wildly wrong attempts to guess a package name from a file name may be).

Now, when it comes to use cases for executing packages inside a module:

   ./python -m test.regrtest  (I use this one all the time)
   python -m pychecker.checker (I should use this more than I do...)
   Test modules embedded inside a package [1]

I forget who first described the use case in [1] to me, but it was 
instrumental in convincing me the current behaviour was a bug that 
should be fixed. SF Bug #1510172 is currently sitting open, pending a 
resolution of this question (i.e. am I correct in thinking that this is 
a bug that should be fixed, or are we better off keeping main module 
behaviour consistent between direct execution and the -m switch?).

Cheers,
Nick.

[1]
http://mail.python.org/pipermail/python-dev/2006-June/066680.html




-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list