-4

I'm not sure if this is a duplicate question. I was reading information online (including here, e.g. How to get a function name as a string in Python?) and messing around with the various suggestions, but the various information is either outdated/not for my specific use case/I am simply implementing it incorrectly.

The problem:

I'm passing the method of an object as a parameter. I would like to know what the full name of this object and method is.

Example code (where I'm am at thus far):

class test():
  def asdf():
    print('asdf')

def magic(command):
  print('command is:', command.__name__)

magic(test.asdf)

The goal would be to go from having magic() outputting 'command is: asdf' to 'command is: test.asdf' since that's the full name of the parameter.

2 Answers2

2

Use __qualname__.

>>> print(test.asdf.__qualname__)
test.asdf
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • This only applies to the very specific case of an unbound method of a class. If I do something like `x = "asdf"; print(x.lower.__qualname__)`, I'm not going to get `x.lower`. – user2357112 Aug 24 '17 at 19:38
  • 1
    In general, this will fail for all instance methods. – user2357112 Aug 24 '17 at 19:39
1

Just to be clear, you are not passing the "method of an object as parameter" but just a function name that is inside a class definition.

To pass a "method of an object" you have to actually create an object and the code would look like this:

class test():
  def asdf():
    print('asdf')

def magic(command):
  print('command is:', command.__func__.__qualname__)
  # Returning the object to which this method is bound just to ilustrate
  return command.__self__

magic(test().asdf)

"method of an object" = Instance methods