Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to create a python object where every attribute is None

I’m not sure if this can be done, but I would like an object where you can query any attribute, and it just returns None, instead of an error.

eg.

>>> print(MyObject.whatever)
None
>>> print(MyObject.abc)
None
>>> print(MyObject.thisisarandomphrase)
None

without manually assigning all of these values in the object’s __init__ function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can define __getattribute__:

class MyObject:
    def __getattribute__(self, name):
        return None  # or simply return
    
x = MyObject()
print(x.abc)
print(x.xyz)

output:

None
None

NB. note that is might not work with all attributes, there are reserved words, e.g. x.class

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading