Padraic Cunningham Padraic Cunningham - 25 days ago 12
Python Question

Check if certain operators are being used in a function

I want to prohibit certain operators being used in a function, for example, say I want to make sure the

**
power operator is not being used in the following function:

def pow(x, y):
return x ** y


I have used
inspect.getsource
to get the source and checked if
"**"
is in the source but that will wrongly cause an assert error if there happens to be
"**"
in the source elsewhere so how to actually check the code for the existence of a particular operator?

Answer

I'd personally go for Ashwini's answer if you have 3.4 at hand, however, if you need to be a bit more compatible and don't mind parsing the source, then you can make use of ast, eg:

import inspect
import ast

def pow(x, y):
    return x ** y

nodes = ast.walk(ast.parse(inspect.getsource(pow)))
has_power = any(isinstance(node, ast.Pow) for node in nodes)
Comments