1

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:

import sys
sys.path.append('./module')

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

assert blue.name == Color.BLUE.name # true
assert blue.value == Color.BLUE.value # true
assert blue == Color.BLUE  # false

Run script2.py, get exception:

  File "/Users/python/script2.py", line 9, in <module>
    assert blue == Color.BLUE  # false
AssertionError

Why the third assertion is not true? how to make it true?

martineau
  • 119,623
  • 25
  • 170
  • 301
xyshell
  • 41
  • 5
  • 1
    Short answer: don't mess with `sys.path` -- by importing the module via a different name, you get a copy of that module, not the original; so everything in that copy will fail `is` tests, and the case of `Enum`, even equality tests can fail. – Ethan Furman Nov 12 '20 at 21:36
  • @EthanFurman Interesting! Thanks for you response – xyshell Nov 12 '20 at 21:48
  • @EthanFurman Can I ask a follow-up question? 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 writes 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? – xyshell Nov 12 '20 at 22:02
  • 2
    You'll need to make that an actual question -- answering in a comment would not be easy, nor useful for others. Feel free to post the link here. – Ethan Furman Nov 12 '20 at 22:05
  • @EthanFurman Here it is! https://stackoverflow.com/questions/64812916/how-to-use-others-code-as-a-module-in-my-project – xyshell Nov 12 '20 at 22:43

0 Answers0