Skip to content

Instantly share code, notes, and snippets.

@motivic
Created August 30, 2016 13:05
Show Gist options
  • Select an option

  • Save motivic/d90082b1d09b7cebb5ab5c34f74e37c5 to your computer and use it in GitHub Desktop.

Select an option

Save motivic/d90082b1d09b7cebb5ab5c34f74e37c5 to your computer and use it in GitHub Desktop.

Revisions

  1. motivic created this gist Aug 30, 2016.
    18 changes: 18 additions & 0 deletions const.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    # http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991
    # Put in const.py...:
    class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
    if self.__dict__.has_key(name):
    raise self.ConstError, "Can't rebind const(%s)"%name
    self.__dict__[name]=value
    import sys
    sys.modules[__name__]=_const()

    # 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__