Specialized @property decorators in python
<p>I have a few classes each of which has a number of attributes. What all of the attributes have in common is that they should be numeric properties. This seems to be an ideal place to use python's decorators, but I can't seem to wrap my mind around what the correct implementation would be. Here is a simple example:</p>

<pre><code>class Junk(object):
    def __init__(self, var):
        self._var = var

    @property
    def var(self):
        """A numeric variable"""
        return self._var

    @var.setter
    def size(self, value):
        # need to make sure var is an integer
        if not isinstance(value, int):
            raise ValueError("var must be an integer, var = {}".format(value))
        self._var = value

    @var.deleter
    def size(self):
        raise RuntimeError("You can't delete var")
</code></pre>

<p>It seems to me that it should be possible to write a decorator that does everything so that the above can be transformed into:</p>

<pre><code>def numeric_property(*args, **kwargs):
    ...

class Junk(object):
    def __init__(self, var):
        self._var = var

    @numeric_property
    def var(self):
        """A numeric variable"""
        return self._var
</code></pre>

<p>That way the new <code>numeric_property</code> decorator can be used in many classes.</p>

<p>You may just create a function that does it for you . As simple as it can get, no need to create a custom descriptor:</p>

<pre><code>def numprop(name, privname):
    @property
    def _numprop(self):
        return getattr(self, privname)

    @_numprop.setter
    def _numprop(self, value):
        if not isinstance(value, int):
            raise ValueError("{name} must be an integer, {name} = {}".format(value, name=name))
        setattr(self, privname, value)

    @_numprop.deleter
    def _numprop(self):
        raise RuntimeError("You can't delete var")
    return _numprop


class Junk(object):
    def __init__(self, var):
        self._var = var
    var = numprop("var", "_var")
</code></pre>

python python-3.x decorator python-decorators