aselimkaya
aselimkaya

Reputation: 121

Use enum instances in another class in Python3

I have an enum class called UsedPlatforms:

from enum import Enum

class UsedPlatforms(Enum):
    PROD = 1,
    TEST = 2

I want to use this enum in another python class like:

import UsedPlatforms

def foo(platform):
    if platform == UsedPlatforms.PROD:
        print("Did it!")

foo(platform=UsedPlatforms.PROD)

But when I run second script, I get an error like:

Traceback (most recent call last):
  File "/home/user/Projects/EnumTest/test.py", line 9, in <module>
    foo(platform=UsedPlatforms.PROD)
AttributeError: module 'UsedPlatforms' has no attribute 'PROD'

Process finished with exit code 1

I think I couldn't import my enum class properly or I didn't know how to use enums between classes, or smth. So, what should I do to use my enum class in another classes?

Thanks!

Upvotes: 8

Views: 12612

Answers (1)

Yunus İrhan
Yunus İrhan

Reputation: 136

If your enum class contained in a file named UsedPlatform.py, then you should change your import statement in test.py to:

from UsedPlatforms import UsedPlatforms

If the file you are trying to import is inside a folder you need :

from folder.FileWithoutExtension import <ClassName/Enum>

enter image description here

Upvotes: 12

Related Questions