0

I have a module-level configuration variable that should assume function values (callable, and this callable will later be accessed and called). I want to set this variable only via an initialize() method, and have read-only access to it afterwards. If the value wasn't to be called as a function, using a property would serve the purpose. However, since I am going to use it as a callable this doesn't work. What are other alternatives to achieve this?

martineau
  • 119,623
  • 25
  • 170
  • 301
Hoda
  • 280
  • 2
  • 5
  • Python doesn't have constant variables, there really is no way of achieving this withouth seriously hacking the runtime. Just learn to live without it (note, `property` doesn't really help prevent anyone with even minimal motivation to subvert your "read only" property) – juanpa.arrivillaga Nov 10 '21 at 01:07
  • See [my answer](https://stackoverflow.com/a/3712574/355230) to the question [Can I prevent modifying an object in Python?](https://stackoverflow.com/questions/3711657/can-i-prevent-modifying-an-object-in-python) – martineau Nov 10 '21 at 01:54
  • Thanks for the comments. My main intention is not really to enforce read-only, but to discourage accessing the variable directly, the same way as using a protected attribute combined with a property accessor works. – Hoda Nov 10 '21 at 02:17
  • You can name things starting with double underscores (`'__'`) to discourage accessing them directly outside the class because Python will mangle the name. See [**private name mangling**](https://docs.python.org/3/reference/expressions.html#atom-identifiers) in the documentation. – martineau Nov 10 '21 at 22:06
  • Thanks for the reference. The desired behavior here is to allow reads from outside the module. E.g. a dependency configuration variable that is set from outside a library at the time we initialize the dependency and can be read in various places within the library. – Hoda Nov 10 '21 at 22:16

0 Answers0