1

I'd like to grab the code from actual python objects. This is the opposite idea of AST and parse, I have an object in memory and I want to recreate the source code. I don't want to get down to the byte code that's excessive, I just want a representation of the code that made the object:

In [24]: from django.apps import apps
In [25]: x= apps.get_app('accounts')

In [26]: x
Out[26]: <module 'mysite.accounts.models' from '/home/cchilders/work_projects/mysite/mysite/accounts/models.py'>

In [27]: x.
x.BusinessUnit                       x.models           

In [35]: bizunit = x.BusinessUnit

In [36]: type(bizunit)
Out[36]: django.db.models.base.ModelBase

import something

bizunit_code = something.something(bizunit)

I want the source of all models, but using ast seems too hairy especially since django provides the apps module to grab all models. Now I just need to untranslate it

Thank you

codyc4321
  • 9,014
  • 22
  • 92
  • 165
  • 1
    must it work for any object, or only a limited set? do you expect to have access to the sources? If you do have access, you can write a parser that looks for the string `class ` in the object's namespace. If the set is very limited and you want a quick test you can always override the `__repr__` method of those objects with the string you want to become. Let me know if any of this would be OK to take a try – fr_andres Mar 21 '16 at 23:20
  • 1
    nevermind, Simeon nailed it – fr_andres Mar 21 '16 at 23:25
  • it has to work for all custom written models. I can grab all dirs under main project folder to check if the app I get is custom or 3rd party, but it's faster to use the apps and just check if the model is in our source – codyc4321 Mar 21 '16 at 23:25

2 Answers2

2

You may be able to obtain the source code using:

import inspect
print(inspect.getsource(biz unit))

This only works when the argument is a module, class, method, function, traceback, frame, or code object. If Python is unable to obtain the source code then this will raise a IOError.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
0

If you want to reconstruct source text from an AST, you can build a prettyprinter.

See my SO answer on how to do this: https://stackoverflow.com/a/5834775/120163

Community
  • 1
  • 1
Ira Baxter
  • 93,541
  • 22
  • 172
  • 341