Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a no-op or dummy class in Python

Tags:

python

Let's say I have code like this:

foo = fooFactory.create()

For various reasons, fooFactory.create() could fail to create an instance of Foo.

If it does, I want fooFactory.create() to return a dummy/no-op object. This object should be completely inert - no matter how it is used, it should not do anything or throw any exceptions. Note that foo does not have methods that return values.


I've considered the following options.

First, create a mock. The upside of this is that it's easy and gives me exactly what I want. The downside is that it feels odd to use a mock in production code. More importantly, I have no control over the mock library and so its behavior could change at some point and break my application.

Second, create a dummy NoopFoo/ DummyFoo class. I then manually implement the methods it needs to support, and just put pass in the method bodies. The upside of that I know it will never break my application. The downside is that if other methods of Foo are used in future, I have to know to update NoopFoo/ DummyFoo ... or my application may break.

Is there a better option than either of these? Note that I'm new to Python so if it involves more advanced Python features, I would appreciate a little more information. Thanks!

like image 256
ck. Avatar asked Nov 27 '22 17:11

ck.


1 Answers

You ask for an object that does nothing. An instance of object does precisely that.

def create():
    return object()

On the other hand, you might actually want it to do something. You might want it to have methods that execute and return None. You might return an instance of this class:

In [1]: class Nop(object):
   ...:     def nop(*args, **kw): pass
   ...:     def __getattr__(self, _): return self.nop
   ...:     

In [2]: n=Nop()

In [3]: n.foo
Out[3]: <bound method Nop.nop of <__main__.Nop object at 0x7f9fec034650>>

In [4]: n.foo()

In [5]: n.foo(1,2,3)
like image 184
Robᵩ Avatar answered Dec 22 '22 05:12

Robᵩ