0

like in PHP you can do

class C {
    private const FOO=123;
}

for constants that are only relevant inside the class/not part of the public API, does Python support something similar?

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • And you can use the `@property` method decorator to make the value read only (i.e. a constant), `@property def __foo(self): return 123` – MatsLindh Mar 31 '22 at 09:15
  • 1
    I think https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes answers the "private" part, for constants there is https://mypy.readthedocs.io/en/stable/final_attrs.html ...in both cases it is not enforced by the runtime, it's convention (and in case of mypy, optional type checking) only – Anentropic Mar 31 '22 at 09:15
  • 1
    `@property` (i.e. a getter without a setter) is not the same as `const`, though for many use cases the behaviour will be similar – Anentropic Mar 31 '22 at 09:18
  • I'm not implying that it is _the same_, but that it will allow you to emulate it in a slightly pythonic way. `__` isn't really private either, so you can always get around these limitations in some way. – MatsLindh Mar 31 '22 at 09:27
  • totally agree :) – Anentropic Mar 31 '22 at 09:30
  • No, Python *doesn't have access modifiers* and *all attributes are public always*. It also, more regrettably, doesn't support constants. Internal, non-public parts of the API are conventionally named with a single leading underscore. – juanpa.arrivillaga Mar 31 '22 at 09:42

0 Answers0