Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a function exist (but not inherited) in python?

Tags:

python

Kind of related to this question:

https://stackoverflow.com/questions/8708525/how-to-check-if-mako-function-exist

I want to check if a function exists for a given class, but not inherited, so that the parent can called the child's function, since otherwise it would result in an infinite recursion..

edit:

it actually gives a maximum stack level error, which is the same.

the equivalent code would be:

class A(object):
    def f(x):
        b = B()
        b.f()

class B(A):
    pass

a = A()
a.f()

i understand this is not clean or preferred, but it is what the template translates to, and I dunno how to check for it otherwise.

like image 909
Timmy Avatar asked Jan 03 '12 06:01

Timmy


People also ask

How do you check inheritance in Python?

Two built-in functions isinstance() and issubclass() are used to check inheritances. The function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each and every class in Python inherits from the base class object .

How do you check if a function is executed in Python?

import functools def calltracker(func): @functools. wraps(func) def wrapper(*args): wrapper. has_been_called = True return func(*args) wrapper. has_been_called = False return wrapper @calltracker def doubler(number): return number * 2 if __name__ == '__main__': if not doubler.

How do you avoid inheritance in Python?

The way to "avoid" inheritance here would be to rename _private_var and make it a class-private name. i.e. __private_var . If you do this, running your code will cause an AttributeError: 'Child' object has no attribute '_Parent__private_var' (note the _Parent prefix automatically added).

Does Isinstance check subclass?

isinstance() checks whether or not the object is an instance or subclass of the classinfo.


2 Answers

I want to check if a function exists for a given class, but not inherited

Yes, you can check the class dictionary directly. Either use the __dict__ attribute or the built-in vars() function::

>>> class A(object):
        def f(x):
            pass

>>> class B(A):
        def g(x):
            pass

>>> 'f' in vars(B)
False
>>> 'g' in vars(B)
True
like image 145
Raymond Hettinger Avatar answered Nov 09 '22 23:11

Raymond Hettinger


If what you need is to check whether the method is defined directly in instance's class and not in one of its ancestors then you can try this:

import inspect

def has_method(obj, name):
    v = vars(obj.__class__)
    # check if name is defined in obj's class and that name is a method
    return name in v and inspect.isroutine(v[name])

class A:
    def foo(self):
        print 'foo'

class B(A):
    pass

b = B()
a = A()

print has_method(a, 'foo') # => True
print has_method(b, 'foo') # => False
like image 32
KL-7 Avatar answered Nov 09 '22 23:11

KL-7