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?
-
line number? i think there is no connection via line number and class to find methodMohammad Efazati– Mohammad Efazati2012-01-12 15:09:13 +00:00Commented Jan 12, 2012 at 15:09
-
2Anything is possible. But more importantly... Why would you like to do this?jathanism– jathanism2012-01-12 15:12:38 +00:00Commented Jan 12, 2012 at 15:12
-
2Anything is possible - Citation needed.MattH– MattH2012-01-12 15:19:07 +00:00Commented Jan 12, 2012 at 15:19
Add a comment
|
1 Answer
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