Find all uses of division operator in python code

Viewed 447

I want to find all of the instances in my python code in which the division operator / is used. My first instinct is to use a regular expression. The expression needs to filter out non-division uses of /, i.e. path names. The best I've come up with is [ A-z0-9_\)]/[ A-z0-9_\(]. This would find the division operator in

foo/bar
foo / bar
foo/(bar*baz)
foo / 10
1/2
etc...

but would also match the /s in something like "path/to/my/file"

Can anybody come up with a better regex? Alternatively, is there a non-regex way to find division?

edit: To clarify:

I don't necessarily need to use python to do this. I just want to know the location of division operators so I can manually/visually inspect them. I can ignore commented code

1 Answers

You can parse your Python code into an abstract syntax tree using the ast module, and then walk the tree to find the line numbers where division expressions appear.

example = """c = 50
b = 100
a = c / b
print(a)
print(a * 50)
print(a / 2)
print("hello")"""

import ast
tree = ast.parse(example)
last_lineno = None
for node in ast.walk(tree):
    # Not all nodes in the AST have line numbers, remember latest one
    if hasattr(node, "lineno"):
        last_lineno = node.lineno

    # If this is a division expression, then show the latest line number
    if isinstance(node, ast.Div):
        print(last_lineno)
Related