Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether function contains pass

I have one parent class P and several child classes. The parent class contains the method doSomething(x) defined only as:

def doSomething(self, x):
    pass

Now, some of P's subclasses may have implemented this method, and some have not. Is there any way I can check if doSomething(x) is going to do nothing but pass, at runtime (e.g. if it is implemented, execute it, if not, skip it)?

like image 781
user44697 Avatar asked Aug 17 '26 16:08

user44697


1 Answers

There is no need to do anything here other than just calling doMethod() on the instance. Calling a no-op method is not so costly that detecting when a child class has implemented an override is going to save you anything.

So your number 1 option is to just call the method, and don't worry about it being an empty method. That's what pass is for, to give you an easy parent class method that does nothing.

Next, you state

Parent class contains method doSomething(x)

You can use this to detect if you have that method still; the underlying function for the bound method is going to be the same object:

hook = instance.doSomething
if hook.__func__ is ParentClass.doSomething:
    # they didn't override the method, so nothing needs to be done.

Again, I'm not sure why anyone would want to do that, because that test is not going to save you anything over just using instance.doSomething().

Next, a function that consists solely of the statement pass will be compiled to the same bytecode, always; it's the same bytecode as return None. Compare the bytecode if you must know if a function is empty:

_RETURN_NONE = (lambda: None).__code__.co_code

def is_pass(f):
    return f.__code__.co_code == _RETURN_NONE

This can be applied to any function or method that, in essence, only ever returns None and does nothing else.

Demo:

>>> class P:
...     def doSomething(self, x):
...         pass
...
>>> class Child1(P):
...     def doSomething(self, x):
...         print("We are doing something with {!r}!".format(x))
...
>>> class Child2(P):
...     pass
...
>>> instance1 = Child1()
>>> instance2 = Child2()
>>> instance1.doSomething(42)
We are doing something with 42!
>>> instance2.doSomething(42)
>>> instance1.doSomething.__func__ is P.doSomething
False
>>> instance2.doSomething.__func__ is P.doSomething
True
>>> is_pass(instance1.doSomething)
False
>>> is_pass(instance2.doSomething)
True
>>> def unrelated_function():
...     return 42
...
>>> def another_unrelated_function():
...     pass
...
>>> is_pass(unrelated_function)
False
>>> is_pass(another_unrelated_function)
True

Note how is_pass() works on any function that uses pass.

like image 67
Martijn Pieters Avatar answered Aug 20 '26 07:08

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!