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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@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.
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).
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.