Reputation: 2260
It's been a while that I am struggling with imports in packages. When I develop a package, I read everywhere that it is preferable to use absolute imports in submodules of that package. I understand that and I like it more as well. But then I don't like and I also read that you shouldn't use sys.path.append('/path/to/package')
to use your package in development...
So my question is, how do you develop such a package from zero, using directly absolute imports? At the moment I develop the package using relative imports, since then I am able to test the code I am writing before packaging and installing, then I change the imports once I have a release and build the package.
What is the correct way of doing such thing? In Pycharm for example you would mark the folder as 'source roor' and be able to work as if the package folder was in the path. Still I read that this is not the proper way... what am I missing? How do you develop a package while testing its code?
Upvotes: 0
Views: 494
Reputation: 7211
Your mileage may vary but this is what I usually do:
Within a package (foo
), absolute (import foo.bar
) or relative (import .bar
) doesn't matter to me as long as it works. Sometimes, I prefer relative especially when the project is large and one day I might decide to move a number of source files into a subdirectory.
How do I test? My $PYTHONPATH
usually has .
in it, and my directory hierarchy is like this:
/path/to/foo_project
/setup.py
/foo
/__init__.py
/bar.py
/test
/test1.py
/test2.py
then the script in foo_project/test/test1.py
will be like what you normally use the package, using import foo.bar
. And when I test my code, I will be in the directory foo_project
and run python test/test1.py
. Since I have .
in my $PYTHONPATH
, it will find the directory foo
and use it as a package.
Upvotes: 1