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

4
  • 1
    Out of curiosity, could you tell us why you want to do this? Commented Mar 16, 2022 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 Commented Mar 16, 2022 at 16:23
  • Then I would assume you still want it to return the attribute if the attribute does exist? Commented Mar 16, 2022 at 16:30
  • the answer is no for complicated reasons but your answer will be useful to someone else so thanks anyway :) Commented Mar 16, 2022 at 16:35

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.