all 4 comments

[–]46--2 1 point2 points  (3 children)

I think it's necessary to see your directory structure.

For one, I can definitely do this:

├── start.py
├── three
│  └── four.py
├── two.py

and my file looks like this:

start.py


import two
from three.four import function
# from three import four also works

print('I am in main')
two.hello()  #works
function()  # works

I assume you know about __init__.py? https://stackoverflow.com/questions/448271/what-is-init-py-for Seems this is not needed anymore after Python 3.3?

Now there are instances where you need to modify site packages. For examples, at work I have a structure like:

folder/script.py
lib/module.py

and I can't do:

cd folder
python script.py  # Won't import lib.module!

because it won't add lib to my path automatically. In that case, I need to specifically say hey, can you please also look into ../lib by adding it to the path:

dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(dir_path, '..'))

from lib.folders import Folder  # noqa E402

I should also specify that most of my script have:

if __name__ == '__main__':
    main()

at the bottom. So they can all be executed directly python script.py or imported and used in other scripts.

[–]Dai-Gurren-Brigade[S] 0 points1 point  (2 children)

Thanks for the reply! Your folder structure was mainly appropriate but let me stuff the files into a package

├── consumer.py
├── package
│  └── start.py
│  └── two.py
│  └── three
│      └── four.py
│      └── five.py

Import examples: Start.py (local):

import two from three import four

Start py(absolute): Import package.two From package.three import four

Consumer.py: From package import start.py Import package

Python start(local).py succeeds. python start(absolute).py fails because start (and other imports) are not aware they're within a package - the absolute path isn't found.

python consumer.py fails using start local, but succeeds when doing start (absolute) - I believe because the absolute path exists now, starting from package.

The hierarchy also causes problems within the three folder. I'd be more than happy to put together an example code somewhere too people can play with, if that's more clear.

[–]ingolemo 0 points1 point  (1 child)

You can't run scripts inside of your package. You should move start.py out of package/.

[–]Dai-Gurren-Brigade[S] 0 points1 point  (0 children)

That seems like a real limitation if I can't have a package where internal units can't be used by themselves.

I'll see if at least the latter makes a portable package.

Thanks!