1

Here's a fun one:

I have a python enumeration created in one module and then used both in that module and in another module. When I import the enumeration in the second module, it ends up not matching the value imported in the first module. I want to pass the value "KnownComputers.KILLDEVIL" into the first module from the second module, but when I compare the value I pass in against "KnownComputers.KILLDEVIL" they compare not equal. Weird!

servers.py lives in foo_module/servers.py:

from enum import Enum

class KnownComputers(Enum):
    KILLDEVIL = "killdevil"
    LONGLEAF = "longleaf"
    DOGWOOD = "dogwood"
    WIGGINS = "wiggins"
    ANDREWS_LAPTOP = "andrews_laptop"
    CATHYS_DESKTOP = "cathys_desktop"

used in that module to make a decision: decision.py in foo_module/decision.py:

from servers import KnownComputers

def func( identifier ):
    comp = identifier.which_computer()
    if comp == KnownComputers.KILLDEVIL:
        print( "Found killdevil!")
    else:
        print( "Found nothing!")

(and there's an empty __init__.py in foo_module/)

Then in my second module, in testbed.py of bar_module/testbed.py

from foo_module.servers import KnownComputers
import foo_module.decide

class killdevil_ident:
    def which_computer(self):
        return KnownComputers.KILLDEVIL

ki = killdevil_ident()
foo_module.decide.func(ki)

What I would expect to see printed is Found killdevil! but what is actually printed is Found nothing!. What is going on here and how can I fix this problem?

(Also worth noting: my python path includes both /path/to/foo_module and /path/to because I am overly thorough/confused.)

Andrew
  • 199
  • 1
  • 9

1 Answers1

-1

Ah! Your problem is how you're importing servers.py from foo_module/decide.py: you need to explicitly tell python that servers.py is part of the same module and not part of another module. In particular the import statement needs to change:

from servers import KnownComputers

should become

from .servers import KnownComputers
Andrew
  • 199
  • 1
  • 9
  • Well that's not a very helpful answer. You haven't told me anything about why python would see `/path/to/foo_module/servers.py` as being a different file from `/path/to/foo_module/servers.py` and import it twice. – Andrew Sep 13 '18 at 13:22