Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if argument into method is "self"

In the question How can I find the number of arguments of a Python function? code is given showing how to using inspect.getfullargspec to get information of a function. However, is there any way to verify whether one of the arguments for the function is self? Is it possible to identify if the first method argument is self Python 2, by somehow check if the first argument of a given function is a reference to the method's object?

For example, the first argument in the function step is technically self even though someone has decided to be evil and rename self to what.

class TestNode(object):

    def __init__(what, bias=0):
        what.bias = bias

    def update(what, t, x):
        return t / x * what.bias

However, the first argument in the function lambda self: self+1 despite someone being evil and naming an argument self is not actually the self using in Python objects.

like image 375
Seanny123 Avatar asked Oct 29 '25 13:10

Seanny123


1 Answers

If we take a step back from argument inspection and think of this question as a question of determining if a function is a method or not. We can do this with the inspect.ismethod function:

>>> import inspect
>>> class Foo:
...     def bar(self):
...         pass
...
>>> inspect.ismethod(Foo().bar)
True

If the function is a bound method we can safely assume that the first passed argument to this method will be self.

Note that in Python 2.X, this will return True for unbound methods (e.g. Foo.bar) whereas in 3.X it will return True only if the method is bound.

We can take this one step further by using getmembers and actually determine what the value of self is for this bound method:

>>> dict(inspect.getmembers(Foo()))["bar"].__self__
<__main__.Foo object at 0x7f601eb50a58>

Which returns the Foo() instance that this bar method is bound to. In Python 2.X, __self__ will be None if the instance is unbound, which is how you differentiate between bound and unbound methods.

like image 156
Matthew Story Avatar answered Nov 01 '25 01:11

Matthew Story



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!