-2

Is there a way to get a full name (dot separated path of a function including its name) of a standard library function? For example:

import sys
import os
from random import choice

my_function = choice([sys.exit, os.path.join, os.getcwd])

print(my_function) # Somehow generate full name of the built-in function
# Would expect to get one of 'sys.exit', 'os.path.join' or 'os.getcwd'
niekas
  • 8,187
  • 7
  • 40
  • 58

1 Answers1

2

You can get the information you're looking for using the __module__ and __qualname__ attributes of a function (under Python 3). For example:

>>> import sys
>>> func = sys.exit
>>> print('{}.{}'.format(func.__module__, func.__qualname__))
sys.exit

This also works for class members:

>>> import email.message

>>> func = email.message.Message.get_payload
>>> print('{}.{}'.format(func.__module__, func.__qualname__))
email.message.Message.get_payload

It's a little more work under Python 2.x because the __qualname__ attribute isn't available:

>>> print('{}.{}.{}'.format(func.__module__, func.im_class.__name__, func.__name__))
larsks
  • 277,717
  • 41
  • 399
  • 399
  • For `os.path.join` I get `"posixpath.join"`, however I would expect `"os.path.join"`. – niekas Apr 23 '19 at 18:13
  • `os.path` is a bad test case, because that actually ends up being `posixpath` or `macpath` or `ntpath`, etc., depending on the platform. So you're actually getting the correct answer. – larsks Apr 23 '19 at 18:15
  • It is strange that you have chose to use `func.__qualname__` instead of `func.__name__`. Whats the difference? – niekas Apr 23 '19 at 18:17
  • Compare the output of `email.message.Message.get_payload.__name__` and `email.message.Message.get_payload.__qualname__`. – larsks Apr 23 '19 at 18:19
  • So the `__name__` returns only the function name, e.g. `'get_payload'`, and `__qualname__` includes the class name too, e.g. `'Message.get_payload'`. Great! Thank you @larsks! – niekas Apr 23 '19 at 18:23