1

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

aloea
  • 191
  • 1
  • 12
  • 1
    Out of curiosity, could you tell us why you want to do this? – Stuart Mar 16 '22 at 16:19
  • I'm making a spreadsheet and I want the cells to be empty if the attribute doesnt exist in that particular object – aloea Mar 16 '22 at 16:23
  • Then I would assume you still want it to return the attribute if the attribute does exist? – Stuart Mar 16 '22 at 16:30
  • the answer is no for complicated reasons but your answer will be useful to someone else so thanks anyway :) – aloea Mar 16 '22 at 16:35

4 Answers4

3

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

mozway
  • 194,879
  • 13
  • 39
  • 75
0

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

Senpai
  • 11
  • 1
0

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
Stuart
  • 9,597
  • 1
  • 21
  • 30
0

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
DarkKnight
  • 19,739
  • 3
  • 6
  • 22