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

3
  • 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 <NAME> 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 Commented Mar 21, 2016 at 23:20
  • 1
    nevermind, Simeon nailed it Commented Mar 21, 2016 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 Commented Mar 21, 2016 at 23:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yep that works perfectly. for some reason I thought expect was only doing bytecode. What is the module that lets you go step by step in the bytecode?
@codyc4321: that's import dis; dis.dis(obj)
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

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.