samedi 22 février 2020

How to get the source code of a file where an object is created in Python?

In my main.py I have the following Python code:

from tasks import SimpleTask
from reflectors import Reflector

task = SimpleTask()

source_code = Reflector().get_source_code(task)

I want to get the source code of main.py from inside the Reflector.get_source_code() using only the parameter task passed.

If I do the following in Reflector.get_source_code() using Python's inspect module:

def get_source_code(self, task):
  return str(inspect.getsource(inspect.getmodule(task)))

I get the source code of tasks module where SimpleTask class is defined.

However, I want to get source code of main.py (the file where task object is created).

I have managed to do the following:

source_code = Reflector().get_source_code(lambda: task)

def run(self, task_callback):
  source_code = str(inspect.getsource(inspect.getmodule(task_callback)))

However, I don't like the lambda: task syntax.

Is there any way to achieve this without the lambda hack?

I would be grateful.





Aucun commentaire:

Enregistrer un commentaire