0

What is the best way to get a string version of a builtin function in Python?

i.e.

>>> import operator
>>> gt = operator.gt
>>> gt
<function _operator.gt>
>>> str(gt)
'<built-in function gt>'

What is the best way to get > back from gt? (Note: I only actually need this for these operators: >, <, >=, <=, == and !=).

rafaelc
  • 57,686
  • 15
  • 58
  • 82
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106

2 Answers2

3

You could access the doc attribute of the built-in function which contains useful comments describing the function.

>>> operator.lt.__doc__
'lt(a, b) -- Same as a<b.'
>>> operator.gt.__doc__
'gt(a, b) -- Same as a>b.'
>>> operator.eq.__doc__
'eq(a, b) -- Same as a==b.'
>>> operator.ne.__doc__
'ne(a, b) -- Same as a!=b.'
Milton Arango G
  • 775
  • 9
  • 16
1

Building on top of the answer given by, @Milton we can do:

import re, operator

def get_symbol(op):
    sym = re.sub(r'.*\w\s?(\S+)\s?\w.*','\\1',getattr(operator,op).__doc__)
    if re.match('^\\W+$',sym):return sym

Examples:

 get_symbol('matmul')
'@'
get_symbol('add')
 '+'
get_symbol('eq')
'=='
get_symbol('le')
'<='
get_symbol('mod')
'%'
get_symbol('inv')
'~'
get_symbol('ne')
'!='

Just to mention a few. You could also do:

{get_symbol(i):i for i in operator.__all__} 

This gives you a dictionary with the symbols. You will see that somethings like abs gives gives incorrect since there is no symbolic version implemented

Onyambu
  • 67,392
  • 3
  • 24
  • 53