1

I'm dealing with an "apparently" simple problem with enums in Python that i cannot figure out how to solve. I just need to load different values for an enum in different environments (dev and prod). Ex:

in dev environment I`d like to define:

from enum import Enum

class PortsDev(Enum):
    service_1 = 5000
    service_2 = 5001
 

in prod environment I`d like to define:

from enum import Enum

class Ports(Enum):
    service_1 = 3000
    service_2 = 3001
 

I'm using conditional import, as:

if os.getenv("APPLICATION_CONFIG") == "production":
    from .services_ports import Ports
else:
    from .services_ports import PortsDev as Ports 

It works, but, the pre-commit fails on mypy with error.

Does anyone have a suggestion for a better way to do this?

Thanks in advance

  • Why not combine the two classes (e.g. suffix the enum values with `_DEV or _PROD`? I don't know about your specific use case, but I don't see why the two cannot be combined. – BrokenBenchmark Jan 11 '23 at 19:16
  • if it fails, do you have an error message? – recursive_tree Jan 11 '23 at 19:36
  • If the two enums have the same structure, I'd just do `if TYPE_CHECKING: from .ports import Ports; elif os.getenv(...) == 'prod': from .ports import Ports; else: from .ports import PortsDev as Ports`. It will work the same way on run time, but `mypy` will treat `Ports` as one enum instead of difficult-to-imagine union. – STerliakov Jan 11 '23 at 20:07
  • @BrokenBenchmark because these enums serve different purpose and have nothing in common? It can even make the values non-unique. Current pattern allows to pick one of port sets and use them interchangeably, while your prefixes idea requires all users to pick manually (making testing and mocking very complicated). – STerliakov Jan 11 '23 at 20:09
  • 1
    In that case, perhaps it would be a good idea to make a config file? I struggle to see why there should be two separate classes that do similar things. – BrokenBenchmark Jan 11 '23 at 20:12
  • Instead of a two enums and a conditional import, use the condition to specify which version of a single `Ports` enum is created. – Ethan Furman Jan 11 '23 at 21:13
  • This does not look like a good use case for an enum. Maybe a NamedTuple is better – Wombatz Jan 12 '23 at 13:23

0 Answers0