Re: problem with import / namespace
- From: Laszlo Nagy <gandalf@xxxxxxxxxxxx>
- Date: Wed, 21 May 2008 15:46:39 +0200
ohad frand wrote:
Hi
I have a problem that the solution to it must be very simple but i couldnt fint it's answer in the internet so far (i searched for couple of days)
the problme is as follows:
i have two directories e.g. "\\1" and "\\2"
in each directory i have two files with the same names e.g. "tmp1.py" and "tmp2.py"
So this is what you have:
/1/tmp1.py
/1/tmp2.py
/2/tmp1.py
/2/tmp2.py
each tmp2.py file imports tmp1 from its same directory (import tmp1) - thats the problem
if i execute one file (\\1\tmp2.py) than the execution is ok
but when i try after that to execute the second file (\\2\tmp2.py) than the tmp1 file from the wrong directory ( - directory 1 in this case) is imported instead.
When you try to import a module, python starts to search for it. The was it does the search is very well defined. It mostly depends on the current directory and sys.path. You can read more about this here:
http://docs.python.org/tut/node8.html#searchPath
This is very basic thing - you should read and go through the tutorial before asking questions like this. :-)
i tried many things to try to solve it, i removed the previous path from sys.path and added the new one, i tried to change current working directory with os.chdir()The problem is still not well defined. Python works as expected and documented, but apparently you do not know how to import 1/tmp2.py from 2/tmp1.py. There are several ways to do it, and we cannot tell which one is correct. It depends on what are these modules for.
I tried to delete from locals and from globals the name tmp1 before running the second file but nothing worked.
please help
Here are the solution that you would use (most likely) as a beginner:
#1 first, rename your "1" and "2" directories to "one" and "two". If you are creating a package with modules, then you have to define the package's name with its directory. Since identifiers cannot begin with digits in Python, you need to use an identifier-like name for your subdirs. It is a good idea anyway. A package name called "1" would tell nothing about what it does?
#2 place your main application in /app/app.py
#3 create /app/one/__init__.py and /app/two/__init__.py files (they can be empty)
- inside your app.py file either make sure that the current dir is /app, or insert /app in the first place in sys.path
Then for example, inside two/tmp1.py you can do this:
import one.tmp1
import one.tmp2
import two.tmp1
one.tmp1.somefunc()
two.tmp1.somefunc()
You got the idea.
Laszlo
.
- Prev by Date: Re: C-like assignment expression?
- Next by Date: Re: Struct usage and varying sizes of h, l, etc
- Previous by thread: about python modules
- Next by thread: Re: problem with import / namespace
- Index(es):
Relevant Pages
|
|