2

I'm attempting a fairly typical if/else -> CONSTANT = ... pattern in python but getting a pyright error that "... is constant (because it is uppercase) and cannot be redefined" (reportConstantRedefinition). While this is not a syntax error, I'm trying to understand how to avoid the pyright warning and -- more importantly -- what the proper pattern is.

My constant is defined based on an if statement. E.g.:

if os.getenv('DEBUG'):
  API_HOST = 'http://STAGING/'
else:
  API_HOST = 'http://PROD/'

It's on the last line that pyright gives the error ""API_HOST" is constant (because it is uppercase) and cannot be redefined".

I've always thought that was a valid pattern. Is there a better way to do that which isn't just a way to outwit pyright? Why does pyright think I should do? E.g., APIHOST = 'x' if os.getenv('DEBUG') else 'y' would work but is harder to read and not scalable.

(I also tried to predefine the variable (API_HOST: str) so that it's clear that it's not unbound (which it can't be) but that just gives me a "redefine" error on both lines.)

Mark Byrne
  • 85
  • 1
  • 5
James
  • 21
  • 1
  • 1
    This looks like a bug in pyright, it should realize that the `if` and `else` are mutually exclusive, so you're not changing a constant. – Barmar Mar 30 '23 at 16:23
  • 1
    I tried finding it in the pyright issues, but couldn't. I suggest you report it as a bug. – Barmar Mar 30 '23 at 16:41
  • 1
    `API_HOST = 'http://STAGING/' if os.getenv('DEBUG') else 'http://PROD/'` – sinoroc Mar 30 '23 at 18:44

1 Answers1

1

According to one maintainer of pyright this behaviour is by design.

They say:

A constant (by definition) can have only one statically-determined value. If it can have different values at runtime based on dynamic behaviours, then it's a variable, not a constant.

I reported this as a bug, but it was closed with that reasoning: https://github.com/microsoft/pyright/issues/5265

(I would not agree because than there would be no constants in Python because no object is determined statically in Python. I would define a constant as a variable that does not get modified after definition).

Pascal Rosin
  • 1,498
  • 16
  • 27