2

File structure is:

├── module
│   ├── script1.py
│   ├── enums.py
├── script2.py

enums.py:

from enum import Enum, auto
        
class Color(Enum):
    RED = auto()
    BLUE = auto()

script1.py:

from enums import Color

blue = Color.BLUE

script2.py:


from module.enums import Color
from module.script1 import blue

assert blue.name == Color.BLUE.name
assert blue.value == Color.BLUE.value
assert blue == Color.BLUE

Run script2.py, get exception:

Traceback (most recent call last):
  File "/Users/python/py_helloworld/script2.py", line 2, in <module>
    from module.script1 import blue
  File "/Users/python/py_helloworld/module/script1.py", line 1, in <module>
    from enums import Color
ModuleNotFoundError: No module named 'enums'

What if module is written by others and I just want to use it in my project by copy-pasting it into my project folder without changing his code. When he wrote the module, since his pythonPath contains module folder so from enums import Color works. But what can I do instead of sys.path.append the module folder?

PS:

  • I can't sys.path.append('./module') because assert blue == Color.BLUE will be false
xyshell
  • 41
  • 5
  • Maybe this is an error due to a circular import. [Have a look over here](https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python) – statist32 Nov 12 '20 at 22:46
  • Are you sure that both the parent directory and `module` contain a file named `__init__.py`? – Green Cloak Guy Nov 12 '20 at 22:51
  • @statist32 I think if it's circular import, an ImportError will be raised instead of ModuleNotFoundError. – xyshell Nov 12 '20 at 22:55
  • @GreenCloakGuy No `__init__.py` in my case. I'm running on python3.8 so I don't think `__init__.py` need to be explicitly created. – xyshell Nov 12 '20 at 22:57
  • If `module` was written not as a package, such that the fully qualified name of `enums` is just that, it’s questionable at **best** to pretend that it was written as a package named `module` instead. Relative imports can sometimes make code “portable” in this sense, but they can’t hide the difference between “package” and “not”, since Python doesn’t have a notion of a global package. – Davis Herring Nov 13 '20 at 02:28
  • @DavisHerring Are you saying that in order for others to use your code as a package, the package author needs to do everything in relative import? – xyshell Nov 13 '20 at 03:13
  • @xyshell: I’m saying that doing so somewhat increases the chance of being able to copy one project’s files into a subdirectory of another. That doesn’t make that practice **advisable**! The only real answer is to install packages, not copy them like NPM does. – Davis Herring Nov 13 '20 at 03:24
  • @DavisHerring Interesting! – xyshell Nov 13 '20 at 03:28

0 Answers0