G
George P
I've run into a strange package related namespace problem.
Follow these steps (on UNIX system) to illustrate:
-------------------------
mkdir /tmp/mypkg
cd /tmp/mypkg
touch __init__.py
echo 'import os\ndef test():\n print os.getcwd()' > os.py
cd /tmp
echo '#\!/usr/bin/env python\nimport mypkg.os\nmypkg.os.test()' >
test_1.py
echo '#\!/usr/bin/env python\nimport os\nprint os.getcwd()' >
test_2.py
chmod a+x test_*.py
-------------------------
This sets up a minimal package mypkg in /tmp that contains a
sub-module named os. It also sets up a test_1.py and test_2.py script
to illustrate the problem. They do equivalent things (print the cwd)
except test_1.py tries and fails to do it from within the mypkg.os
module.
The problem is then that I can't import the global package "os" into
my mypkg.os packaged module. I've done lots of digging around into
this problem and I think I understand the reasons why this happens.
My question is if anyone can think of an alternative way of
fixing/avoiding this?
The best workarounds I have are:
a) Not use os as my submodule name
b) First import global os in test_1.py and then in mypkg/os.py run
the function as sys.modules["os"].__dict__["getcwd"]()
a) is not a perfect solution because, well, in my example I've used
"os" to illustrate the problem, but really, who's to predict what
global modules might be installed on a system? And besides, isn't this
something that namespaces were supposed to solve?
b) well, that's just plain ugly.
Any other ideas?
thanks,
George
Follow these steps (on UNIX system) to illustrate:
-------------------------
mkdir /tmp/mypkg
cd /tmp/mypkg
touch __init__.py
echo 'import os\ndef test():\n print os.getcwd()' > os.py
cd /tmp
echo '#\!/usr/bin/env python\nimport mypkg.os\nmypkg.os.test()' >
test_1.py
echo '#\!/usr/bin/env python\nimport os\nprint os.getcwd()' >
test_2.py
chmod a+x test_*.py
-------------------------
This sets up a minimal package mypkg in /tmp that contains a
sub-module named os. It also sets up a test_1.py and test_2.py script
to illustrate the problem. They do equivalent things (print the cwd)
except test_1.py tries and fails to do it from within the mypkg.os
module.
The problem is then that I can't import the global package "os" into
my mypkg.os packaged module. I've done lots of digging around into
this problem and I think I understand the reasons why this happens.
My question is if anyone can think of an alternative way of
fixing/avoiding this?
The best workarounds I have are:
a) Not use os as my submodule name
b) First import global os in test_1.py and then in mypkg/os.py run
the function as sys.modules["os"].__dict__["getcwd"]()
a) is not a perfect solution because, well, in my example I've used
"os" to illustrate the problem, but really, who's to predict what
global modules might be installed on a system? And besides, isn't this
something that namespaces were supposed to solve?
b) well, that's just plain ugly.
Any other ideas?
thanks,
George