packages, modules and double imports - oh my!

Chris Withers chris at simplistix.co.uk
Mon Oct 3 06:11:56 EDT 2011


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 at 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 at 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 at 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 at 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 at 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 at 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 at cwlin:~> PYTHONPATH=. python pack/__init__.py
{'MyClass': <class 'pack.module.MyClass'>}
{}
wtf? why aren't these the same registry object?!
Any help appreciated...
Chris
-------------- next part --------------
A non-text attachment was scrubbed...
Name: pack.tgz
Type: application/x-compressed-tar
Size: 426 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20111003/d9c0fe01/attachment.bin>


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /