Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You… can? I mean in the strictest sense you're technically not importing by file path but if you make your folder a module by slapping an __init__.py in there then your relative imports will follow the directory tree. I think as of Python 3.3 the init file is optional so it will do it by default but I can't remember if there are still some cases where it's required. The only thing you can't do is go "up" to a higher directory than the root module.

Also if that doesn't strike your fancy all of the importlib machinery is at your disposal and it's really not very much work to write an import_path() function. It's one of the patterns plug-in systems use and so is stable and expected to be used by end users. No arcane magic required.



> if you make your folder a module by slapping an __init__.py in there then your relative imports will follow the directory tree.

`__init__.py` has nothing to do with making this work. It is neither necessary (as of 3.3, yes, you got it right: see https://peps.python.org/pep-0420/) nor sufficient (careless use of sys.path and absolute imports could make it so that the current folder hasn't been imported yet, so you can't even go "up into" it). The folder will already be represented by a module object.

What `__init__.py` does is:

1. Prevents relative imports from also potentially checking in other paths.

2. Provides a space for code that runs before sub-modules, for example to set useful package attributes such as `__all__` (which controls star-imports).


> if you make your folder a module by slapping an __init__.py in there then your relative imports will follow the directory tree

haha no

> all of the importlib machinery is at your disposal

This breaks all tooling. Awful option.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: