Programmer's Python - Default Methods
Written by Mike James   
Monday, 06 July 2020
Article Index
Programmer's Python - Default Methods
Customizing Delete And Dir

Custom Deleting Attributes

Setting and getting an attribute aren’t the only things you can customize.

You can also set up a custom delete.

There are two standard ways to delete an attribute.

You can use:

del object.attribute

This is efficient but can only be used if you know the object and attribute ahead of time i.e. it is not dynamic.

If this isn’t the case then you can use the:

delattr(object, “attribute”)

function. The difference is that it is slower and the attribute is specified as a string giving its name.

In either case the magic method __delattr__ is called if it is defined in the class for an instance or in the metaclass for a class object.

For example:

class MyClass(metaclass=MyMeta):
    def __delattr__(self, item):
        print("delete called")

You will see the message “delete called” in response to either way of deleting an attribute:

del myObj.myAttribute1

Notice that this is slightly different from the other magic methods in that the class to use to call the method is determined by del or delattr which are not class attributes. However, there is the same potential for infinite recursion if you use del or delattr in __delattr__.

For example:

    def __delattr__(self, item):
        print("delete called")

results in an infinite recursion.

The proper way to do the job is to call the superclass’s __delattr__:

class MyClass(metaclass=MyMeta):
    def __delattr__(self, item):
        print("delete called")

Custom Dir

The dir function will return a list of names of the attributes of an object. You can override the default behavior by defining the __dir__ function. All that __dir__ has to do is return a list or more generally a sequence e.g. tuple, str, etc.. The list is then passed back to dir which sorts it before returning it to the caller.

As always, defining __dir__ in a class overrides the dir operation in any instance of the class, but not the class object, and defining it in the metaclass overrides it for the class object.

For example:

class MyClass(metaclass=MyMeta):
    def __dir__(self):
        return ['C', 'A', 'B']

returns a list of strings which have nothing at all to do with the local variables. If you use:


you will see:

['A', 'B', 'C']

The dir function has sorted the list as promised. It is tempting to use the __dir__ function to do things that have nothing to do with local variables, but this isn’t a generally a good idea because it will confuse any programmer who knows what dir is supposed to do.

By default dir uses the instance and the class __dict__ to discover what attributes have been defined.

Notice that this could be wrong if you have defined a __getattr__ or __getattribute__ function.

In chapter but not in this extract:

  • Slots
  • Index/Key Access




  • The descriptor object can customize access to any attribute via the __get__, __set__ and __delete__ functions which are automatically called on attribute access or deletion.

  • If a descriptor defines __get__ and __set__ then it is a data descriptor; if only __get__ is defined it is a non-data descriptor.

  • Data descriptors cannot be overridden by a definition in the instance, whereas non-data descriptors can be.

  • __getattribute__ is called for every attribute access and if you override it then you override every attribute access.

  • If __getattribute__ fails to find an attribute then it automatically calls __getattr__ if it is defined.

  • __setattr__ is called every time you attempt an assignment to an attribute.

  • You can use __getattr__ to implement default attributes and methods.

  • You can use del or delattr to delete an attribute but in either case __delattr__ is called if it is defined.

  • The __dir__ magic method can be used to define a custom dir command.

  • Slots are just a more efficient way of implementing attributes using a descriptor.

  • Another way of accessing attributes is via the index or key operator []. This can be customized using __getitem__ and __setitem__. There are also a range of additional magic methods that can make attribute access look more like a collection.


Programmer's Python
Everything is an Object
Second Edition

Is now available as a print book: Amazon



  1. Get Ready For The Python Difference
  2. Variables, Objects and Attributes
  3. The Function Object
  4. Scope, Lifetime and Closure
  5. Advanced Functions
  6. Decorators
  7. Class, Methods and Constructors
      Extract 1: Objects Become Classes ***NEW!
  8. Inside Class
  9. Meeting Metaclasses
  10. Advanced Attributes
  11. Custom Attribute Access
  12. Single Inheritance
  13. Multiple Inheritance
  14. Class and Type
  15. Type Annotation
  16. Operator Overloading
  17. Python In Visual Studio Code

 Extracts from the first edition

Advanced Attributes

Related Articles

Creating The Python UI With Tkinter

Creating The Python UI With Tkinter - The Canvas Widget

The Python Dictionary

Arrays in Python

Advanced Python Arrays - Introducing NumPy





or email your comment to:

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.




Last Updated ( Monday, 06 July 2020 )