1

I wish to do some kind of reflection thing where given a line number and a module, I get back the name of the function in that module containing that line. Is this possible in Python?

3
  • line number? i think there is no connection via line number and class to find method Commented Jan 12, 2012 at 15:09
  • 2
    Anything is possible. But more importantly... Why would you like to do this? Commented Jan 12, 2012 at 15:12
  • 2
    Anything is possible - Citation needed. Commented Jan 12, 2012 at 15:19

1 Answer 1

2

There is no built-in way to do this in python. However, you could define a function to do something like that, but it would handle modules as files in your current directory:

import re

def get_function_name(module, line):
    module_file = module.replace('.', '/') + '.py'
    lines = open(module_file, 'r').xreadlines()
    i = line - 1
    try:
        while i:
            tmp = next(lines)
            i -= 1
    except StopIteration:
        raise EOFError('Not enought lines in module %s' % module)
    function_line = next(lines)
    function_name =  re.match('def (\w+)\([^)]*\):', function_line)
    if function_name:
        return function_name.group(1)
    raise ValueError('No function declared on line %s' % line)

This function is opening the module passed as a file, iterating until reached the passed line, and then, searching the name of the function using regular expressions. If there was no function declared on the passed line or the line passed exceeded the number of lines of the file, it will raise an Error. E.g.:

>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.