0

So I have a very simple package with the following structure:

package/
   __init__.py
   a.py
   subpackage/
       __init__.py
       b.py

a.py:
    print __name__
    from .subpackage.b import *

b.py

    print __name__

1) Why if I run python -m a from when inside package it returns: ValueError: Attempted relative import in non-package. But If I leave the package directory and I run python -m package.a it works and prints:

__main__
package.subpackage.b

And also, why does it say __main__ as __name__ for a.py if I am running it as a module with-m option?

2) Why if then I write a c.py module that I put outside package that just imports from package import a I get:

package.a
package.subpackage.b

So I understand that now __name__ from a is not __main__ but why is that the case when I run it with as a module with python -m option. And why if I place that same main.py inside package, then the attempted relative import error appears again?

edgarstack
  • 1,096
  • 1
  • 10
  • 18
  • it varies between python versions, do you mind sharing what's yours? – Taku Mar 26 '17 at 23:16
  • 1
    Note the documentation description for `-m` is: "Searches `sys.path` for the named module and runs the corresponding `.py` file as a script." That's why `__name__` is `__main__`: you're running that `.py` file as a script. As @abccd says, the relative import details vary somewhat between versions; see [this q-and-a](http://stackoverflow.com/q/16981921/1256452) for instance. – torek Mar 26 '17 at 23:59
  • @abccd I am using python 2.7.12 – edgarstack Mar 27 '17 at 09:55

0 Answers0