Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: making a class that return None on any function calls

I was wondering if it is possible to make a class that, always return None no matter what "methods" are called.

For example,

# The following all returns None
Myclass.method1()
Myclass.method2(1, 2, 3)
Myclass.method2(1,2) 

Basically, I want to implement a class, such that

  1. Any non-built-in methods that are not defined by the class are accepted and recognized as valid methods.
  2. All of the methods from point 1 will return None

I know that mock.MagicMock can give me this result, but it is very slow, so I was wondering if theres a better way to do this.

like image 506
user1948847 Avatar asked Feb 27 '26 21:02

user1948847


1 Answers

Yeah, easy.

def return_none(*args, **kwargs):
    """Ignores all arguments and returns None."""
    return None

class MyClass(object):
    def __getattr__(self, attrname):
        """Handles lookups of attributes that aren't found through the normal lookup."""
        return return_none
like image 184
user2357112 supports Monica Avatar answered Mar 02 '26 11:03

user2357112 supports Monica