aloea
aloea

Reputation: 211

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

Upvotes: 1

Views: 859

Answers (4)

Adon Bilivit
Adon Bilivit

Reputation: 27196

I would imagine that if the attribute does actually exist that you'd want its value, therefore I propose:

class MyClass:
    def __init__(self):
        self.a = 1
    def __getattr__(self, name):
        try:
            return super(MyClass, self).__getattr__(name)
        except AttributeError:
            pass
        return None

mc = MyClass()

print(mc.a)
print(mc.b)

Output:

1
None

Upvotes: 0

Stuart
Stuart

Reputation: 9868

In case you still want the class to return actual attributes when they do exist, you could have __getattribute__ catch attribute errors:

class MyObject(object):
    def __getattribute__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            return None

Upvotes: 0

Senpai
Senpai

Reputation: 11

No sure if I understood your question (not very good at english), but i think you could try using hasattr (https://docs.python.org/3/library/functions.html#hasattr) to check if the attribute exist and return wathever you want if it doesnt

Upvotes: 0

mozway
mozway

Reputation: 262114

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

Upvotes: 3

Related Questions