Skip to content

Instantly share code, notes, and snippets.

Created April 1, 2016 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/d3a10247e34468a1d850a02c3f88ac1c to your computer and use it in GitHub Desktop.
Save anonymous/d3a10247e34468a1d850a02c3f88ac1c to your computer and use it in GitHub Desktop.
Sharpened (C#-like) properties in Python
#!/usr/bin/env python2.4
# -*- coding: iso-8859-1 -*-
"""
Property decorator which provides a C#-like syntax for declaring
properties in new-style classes.
Copyright (c) 2006 Håvard Stranden
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Author: Håvard Stranden <havard.stranden@gmail.com>
URL: http://ox.no/software/
License: MIT
"""
import sys
def property(prop):
"""
Decorator for declaring properties in a C#-like manner,
simplifying the use of properties in Python.
Usage:
>>> class A(object):
... def __init__(self):
... self._x = 0
... @property
... def x():
... def get(self):
... print 'get'
... return self._x
... def set(self, value):
... print 'set'
... self._x = value
...
>>> a = A()
>>> print a.x
get
0
>>> print a._x
0
>>> a.x = 1
set
>>> print a.x
get
1
>>> print a._x
1
"""
names = ('get', 'set')
args = {'doc' : prop.__doc__}
def snap(func, event, a):
if event == 'return':
args.update(dict(('f' + name, func.f_locals.get(name)) for name in names))
sys.settrace(None)
return snap
sys.settrace(snap)
prop()
return __builtins__.property(**args)
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment