3

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.

Seanny123
  • 6,594
  • 11
  • 56
  • 106

2 Answers2

5

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.

Matthew Story
  • 2,987
  • 12
  • 24
1

self is not a special argument. The name self has nothing special at all - It is a normal argument just like the others, the only reason it is named self is convention between the programmers.

There is no way you can differentiate a self argument from other arguments, because it is not different at all!

What you can do is check if the function is member of a class - then it becomes a method and will get the instance as first parameter automatically - this is done by the metaclass descriptors as you can see here in the documentation.

if inspect.ismethod() returns True then the first parameter passed to the function will be the instance, regardless of the name.

nosklo
  • 193,422
  • 54
  • 273
  • 281