1

Hello i am trying to create a const in python using this example found from Creating constant in Python (in the first answer from the link) and use instance as module.

The first file const.py has

# Put in const.py...:
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__ in (name):
            raise self.ConstError("Can't rebind const(%s)"%name)
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()

And the rest goes to test.py for example.

# that's all -- now any client-code can
import const
# and bind an attribute ONCE:
const.magic = 23
# but NOT re-bind it:
const.magic = 88      # raises const.ConstError
# you may also want to add the obvious __delattr__

Although i have made 2 changes cause i am using python 3 i still get errors

Traceback (most recent call last):
  File "E:\Const_in_python\test.py", line 4, in <module>
    const.magic = 23
  File "E:\Const_in_python\const.py", line 5, in __setattr__
    if self.__dict__ in (name):
TypeError: 'in <string>' requires string as left operand, not dict

I dont understand what the line 5 error is. Can anyone explain? Correcting the example would also be nice. Thanks in advance.

Community
  • 1
  • 1
BugShotGG
  • 5,008
  • 8
  • 47
  • 63

3 Answers3

4

This looks weird (where did it come from?)

if self.__dict__ in (name):

shouldn't it be

if name in self.__dict__:

That fixes your example

Python 3.2.3 (default, May  3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import const
>>> const.magic = 23
>>> const.magic = 88
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "const.py", line 6, in __setattr__
    raise self.ConstError("Can't rebind const(%s)"%name)
const.ConstError: Can't rebind const(magic)

Do you really need this const hack? Lots of Python code seems to somehow work without it

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 1
    @gnibbler Thanks, i dont really need it but its good to know. I am still learning whatever i can. :) – BugShotGG Oct 03 '12 at 10:25
  • @gnibbler weird thing. I get the error if i try to rebind it in python IDLE but in eclipse it just rebinds with the new value without any errors. hmmm bug of eclipse or something? – BugShotGG Oct 03 '12 at 10:32
  • 2
    @GeoPapas: you are trying to learn whatever you can, that is a good thing. An important thing to learn about Python is that it's usually better to not try to bolt on features from other languages. You end up trading one set of (perceived) problems for another set of (actual) problems. – Ned Batchelder Oct 03 '12 at 12:10
3

This line:

   if self.__dict__ in (name):

should be

   if name in self.__dict__:

... you want to know if the attribute is in the dict, not if the dict is in the attribute name (which doesn't work, because strings contain strings, not dictionaries).

l4mpi
  • 5,103
  • 3
  • 34
  • 54
0

Maybe kkconst - pypi is what you search.

support str, int, float, datetime the const field instance will keep its base type behavior. Like orm model definition, BaseConst is Constant Helper which manage const field.

For example:

from __future__ import print_function
from kkconst import (
    BaseConst,
    ConstFloatField,
)

class MathConst(BaseConst):
    PI = ConstFloatField(3.1415926, verbose_name=u"Pi")
    E = ConstFloatField(2.7182818284, verbose_name=u"mathematical constant")  # Euler's number"
    GOLDEN_RATIO = ConstFloatField(0.6180339887, verbose_name=u"Golden Ratio")

magic_num = MathConst.GOLDEN_RATIO
assert isinstance(magic_num, ConstFloatField)
assert isinstance(magic_num, float)

print(magic_num)  # 0.6180339887
print(magic_num.verbose_name)  # Golden Ratio
# MathConst.GOLDEN_RATIO = 1024  # raise Error, because  assignment allow only once

more details usage you can read the pypi url: pypi or github

same answer: Creating constant in Python

Community
  • 1
  • 1
kaka_ace
  • 347
  • 2
  • 5
  • 7