3

I implemented a python extension module in C according to https://docs.python.org/3.3/extending/extending.html

Now I want to have integer constants in that module, so I did:

module= PyModule_Create(&myModuleDef);
...
PyModule_AddIntConstant(module, "VAR1",1);
PyModule_AddIntConstant(module, "VAR2",2);
...
return module;

This works. But I can modify the "constants" from python, like

import myModule
myModule.VAR1 = 10

I tried to overload __setattr__, but this function is not called upon assignment.

Is there a solution?

MichaelW
  • 1,328
  • 1
  • 15
  • 32

1 Answers1

6

You can't define module level "constants" in Python as you would in C(++). The Python way is to expect everyone to behave like responsible adults. If something is in all caps with underscores (like PEP 8 dictates), you shouldn't change it.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • C does not support symbolic constants of arbitrary type. It is not C++. Only enum-constants are possible, but those are always `int`. And in Python, you _could_ change the setter for an object. But normally one avoids the effort and relies on the convention. – too honest for this site Feb 22 '17 at 14:50
  • @Olaf - True, but in this case the OP is trying to prevent a reference from rebinding, which isn't possible in Python at all. And since Python integers are all immutable objects, `__setattr__` is immaterial. – StoryTeller - Unslander Monica Feb 22 '17 at 14:55
  • 1
    Yes, that would require a "normal" class with all the overhead involved. That's why I agree about relying on the convention (if that was not clear from my comment). – too honest for this site Feb 22 '17 at 14:58
  • It is indeed possible, if the module is replaced with an instance of custom class, but yeah, I wouldn't do it either. Also, `import math; math.PI = 3` – Antti Haapala -- Слава Україні Feb 22 '17 at 19:57