packages, modules and double imports - oh my!

C

Chris Withers

Hi All,

The attached package gives that smallest possible example of problems
I'm hitting with some SQLAlchemy declarative classes.

In short, I want to be able to do:

python -m pack.module and have if the __name__=='__main__' block spit
out the SQL to create the tables necessary for the modules in that class...

So, using the attached package to demonstrate, the first problem I get is:

cwithers@cwlin:~> python -m pack.module
Traceback (most recent call last):
File "/usr/lib64/python2.6/runpy.py", line 121, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib64/python2.6/runpy.py", line 34, in _run_code
exec code in run_globals
File "/home/cwithers/pack/module.py", line 3, in <module>
class MyClass(object):
File "pack/__init__.py", line 7, in __init__
raise Exception('%r registered twice' % self.__name__)
Exception: 'MyClass' registered twice

Looks like I have a pack.module.MyClass and a __main__.MyClass, which
feels like a bug to me...

Ho hum, lets try something different:

cwithers@cwlin:~> python pack/module.py
Traceback (most recent call last):
File "pack/module.py", line 1, in <module>
from pack import MyMeta
ImportError: No module named pack

Meh, okay, so only the path containing the script being run ends up on
PYTHONPATH, okay, so:

cwithers@cwlin:~> PYTHONPATH=. python pack/module.py
Traceback (most recent call last):
File "pack/module.py", line 3, in <module>
class MyClass(object):
File "pack/__init__.py", line 7, in __init__
raise Exception('%r registered twice' % self.__name__)
Exception: 'MyClass' registered twice

....back to square one :-(

cwithers@cwlin:~> python -m pack
/usr/bin/python: pack is a package and cannot be directly executed

That's annoying, why isn't pack/__init__.py's __name__=='__main__' block
executed?

cwithers@cwlin:~> python pack
/usr/bin/python: can't find '__main__.py' in 'pack'

Wha? First I've ever heard of __main__.py... where's that documented?
Anyway:

cwithers@cwlin:~> python pack/__init__.py
Traceback (most recent call last):
File "pack/__init__.py", line 10, in <module>
from pack.module import MyClass
ImportError: No module named pack.module

Oh, right, we're back here..., so lets try:

cwithers@cwlin:~> PYTHONPATH=. python pack/__init__.py
{'MyClass': <class 'pack.module.MyClass'>}
{}

wtf? why aren't these the same registry object?!

Any help appreciated...

Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top