fstab
fstab

Reputation: 5029

More concise form to set a read-only `@property` in python

I know that if I want to set a read-only property in python I can do the following in a class:

class Foo(object):

    @property
    def foo(self):
        return self._foo

but it seems still too long (3/4 lines) in the case I have many of properties as simple as this one.

I know I could code a system myself to create read-only properties, but I would like to avoid to reinvent the wheel.

I am wondering if there are special functions that can do something like:

create_ro_property(self,"foo","_foo",42) # where 42 is the initial value of 42

This would create a read-only property foo that can be set internally to the object via _foo.

any ideas?

Upvotes: 0

Views: 54

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122032

You could do it as follows:

class Foo(object):

    foo = property(lambda self: self._foo)

The @ is just syntactic sugar and a lambda can replace such a trivial def for creating the getter.

Note that this doesn't set the initial value of 42; you would still have to do that e.g. in __init__. Alternatively, perhaps you could do something clever in __getattr__ to return None for missing attributes starting with _, then make the return value self._foo or 42 (or, if 0 is a valid value, 42 if self._foo is None else self._foo).

Upvotes: 3

Related Questions