1

What's the best way in Python to make code independent from where it is located?

In a project of mine I have a lot of code (in different files) which all need to access the same objects defined and created somewhere else.

In a perfect world:

somewhere.py

from registry import register
...
register(Cat(), "cat")
...

somewhere_else.py

from magic import cat
...
cat.pet()
...

However this would most likely involve overriding the import system, so I'm also happy with any implementation that sort of mimics this system, ex. magic.get('cat') instead of from magic import cat.

Any ideas?

Ralf
  • 16,086
  • 4
  • 44
  • 68
Sam Coutteau
  • 357
  • 2
  • 15
  • 2
    Have you tried relative imports? Maybe something like `from ..registry import register` ? The dots allow to access the parent directory. – Ralf Nov 02 '18 at 10:16
  • 1
    Do `somewhere.py`, `somewhere_else.py`, `registry` and `magic` all belong to the same project? Files in the same project should use relative imports like `from .registry import register`. Projects with dependencies on other projects should require all dependencies to be *installed* and thus importable from anywhere. – Aran-Fey Nov 02 '18 at 10:21
  • Check out [this answer](https://stackoverflow.com/a/50193944/1222951). – Aran-Fey Nov 02 '18 at 10:26
  • (They all belong to the same project),It's more when one of the files is moved, rather than relative imports. (for example when the project file structure is changed) – Sam Coutteau Nov 02 '18 at 10:27
  • If you change the project structure then of course you must update the code to reflect it. Any decent IDE should be able to do that for you. – Aran-Fey Nov 02 '18 at 10:30

1 Answers1

0

Structuring your project into sub-packages and importing things in __init__.py could solve your problem (if I understand it correctly). For example:

If your project is structured like:

root
├── animals
│   ├── cat.py
│   ├── dog.py
│   └── __init__.py
└── main.py

you can have:

cat.py:

class Cat:
    pass

dog.py:

class Dog:
    pass

__init__.py

from .cat import Cat
from .dog import Dog

main.py

from animals import Dog, Cat  # we don't specify exact modules, just a sub-package name
# do stuff with these animals
michcio1234
  • 1,700
  • 13
  • 18