Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I restrict objects in Python3 so that only attributes that I make a setter for are allowed?

I have something called a Node. Both Definition and Theorem are a type of node, but only Definitions should be allowed to have a plural attribute:

class Definition(Node):


    def __init__(self,dic):
        self.type = "definition"
        super(Definition, self).__init__(dic)
        self.plural = move_attribute(dic, {'plural', 'pl'}, strict=False)


    @property
    def plural(self):
        return self._plural

    @plural.setter
    def plural(self, new_plural):
        if new_plural is None:
            self._plural = None
        else:
            clean_plural = check_type_and_clean(new_plural, str)
            assert dunderscore_count(clean_plural)>=2
            self._plural = clean_plural


class Theorem(Node):


    def __init__(self, dic):
        self.type = "theorem"
        super().__init__(dic)
        self.proofs = move_attribute(dic, {'proofs', 'proof'}, strict=False)
        # theorems CANNOT have plurals:
        # if 'plural' in self:
        #   raise KeyError('Theorems cannot have plurals.')

As you can see, Definitions have a plural.setter, but theorems do not. However, the code

theorem = Theorem(some input)
theorem.plural = "some plural"

runs just fine and raises no errors. But I want it to raise an error. As you can see, I tried to check for plurals manually at the bottom of my code shown, but this would only be a patch. I would like to block the setting of ANY attribute that is not expressly defined. What is the best practice for this sort of thing?


I am looking for an answer that satisfies the "chicken" requirement:

I do not think this solves my issue. In both of your solutions, I can append the code t.chicken = 'hi'; print(t.chicken), and it prints hi without error. I do not want users to be able to make up new attributes like chicken.

like image 314
mareoraft Avatar asked Aug 09 '15 17:08

mareoraft


People also ask

How do you make an attribute read only in Python?

If you need to make a read-only attribute in Python, you can turn your attribute into a property that delegates to an attribute with almost the same name, but with an underscore prefixed before the its name to note that it's private convention.

Which method is used to set an attribute of the object?

The setAttribute() method sets a new value to an attribute.


1 Answers

The short answer is "Yes, you can."

The follow-up question is "Why?" One of the strengths of Python is the remarkable dynamism, and by restricting that ability you are actually making your class less useful (but see edit at bottom).

However, there are good reasons to be restrictive, and if you do choose to go down that route you will need to modify your __setattr__ method:

def __setattr__(self, name, value):
    if name not in ('my', 'attribute', 'names',):
        raise AttributeError('attribute %s not allowed' % name)
    else:
        super().__setattr__(name, value)

There is no need to mess with __getattr__ nor __getattribute__ since they will not return an attribute that doesn't exist.

Here is your code, slightly modified -- I added the __setattr__ method to Node, and added an _allowed_attributes to Definition and Theorem.

class Node:

    def __setattr__(self, name, value):
        if name not in self._allowed_attributes:
            raise AttributeError('attribute %s does not and cannot exist' % name)
        super().__setattr__(name, value)


class Definition(Node):

    _allowed_attributes = '_plural', 'type'

    def __init__(self,dic):
        self.type = "definition"
        super().__init__(dic)
        self.plural = move_attribute(dic, {'plural', 'pl'}, strict=False)

    @property
    def plural(self):
        return self._plural

    @plural.setter
    def plural(self, new_plural):
        if new_plural is None:
            self._plural = None
        else:
            clean_plural = check_type_and_clean(new_plural, str)
            assert dunderscore_count(clean_plural)>=2
            self._plural = clean_plural


class Theorem(Node):

    _allowed_attributes = 'type', 'proofs'

    def __init__(self, dic):
        self.type = "theorem"
        super().__init__(dic)
        self.proofs = move_attribute(dic, {'proofs', 'proof'}, strict=False)

In use it looks like this:

>>> theorem = Theorem(...)
>>> theorem.plural = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __setattr__
AttributeError: attribute plural does not and cannot exist

edit

Having thought about this some more, I think a good compromise for what you want, and to actually answer the part of your question about restricting allowed changes to setters only, would be to:

  • use a metaclass to inspect the class at creation time and dynamically build the _allowed_attributes tuple
  • modify the __setattr__ of Node to always allow modification/creation of attributes with at least one leading _

This gives you some protection against both misspellings and creation of attributes you don't want, while still allowing programmers to work around or enhance the classes for their own needs.

Okay, the new meta class looks like:

class NodeMeta(type):

    def __new__(metacls, cls, bases, classdict):
        node_cls = super().__new__(metacls, cls, bases, classdict)
        allowed_attributes = []
        for base in (node_cls, ) + bases:
            for name, obj in base.__dict__.items():
                if isinstance(obj, property) and hasattr(obj, '__fset__'):
                    allowed_attributes.append(name)
        node_cls._allowed_attributes = tuple(allowed_attributes)
        return node_cls

The Node class has two adjustments: include the NodeMeta metaclass and adjust __setattr__ to only block non-underscore leading attributes:

class Node(metaclass=NodeMeta):

    def __init__(self, dic):
        self._dic = dic

    def __setattr__(self, name, value):
        if not name[0] == '_' and name not in self._allowed_attributes:
            raise AttributeError('attribute %s does not and cannot exist' % name)
        super().__setattr__(name, value)

Finally, the Node subclasses Theorem and Definition have the type attribute moved into the class namespace so there is no issue with setting them -- and as a side note, type is a bad name as it is also a built-in function -- maybe node_type instead?

class Definition(Node):

    type = "definition"

    ...

class Theorem(Node):

    type = "theorem"

    ...

As a final note: even this method is not immune to somebody actually adding or changing attributes, as object.__setattr__(theorum_instance, 'an_attr', 99) can still be used -- or (even simpler) the _allowed_attributes can be modified; however, if somebody is going to all that work they hopefully know what they are doing... and if not, they own all the pieces. ;)

like image 76
Ethan Furman Avatar answered Sep 22 '22 00:09

Ethan Furman