简体   繁体   中英

How do I get the source for a Python class I declared programmatically?

I'm trying to use inspect.getsource() to get the source of a class that was defined like this:

import inspect

Cat = type('Cat', (), {})

def meow_local(self):
  print("meow")

Cat.meow = meow_local

print(inspect.getsource(Cat))

The error I get from inspect is:

OSError: could not find class definition

It is understandable that inspect does not know the correct place to find the Cat class. Where should I tell inspect to look?

Or is there another way to get the same results?

You don't. And you can't, as there is no source code for it.

inspect.getsource works by finding out the actuall .py file something is defined in, and getting the file lines, as they are on disk, with comments, whitespace, and such.

Even if you fill up all meta-information needed on a programatically defined class to the point you will get a __file__ value, and line information in the code objects, getsource will jsut try to read that file and get the text in there.

You don't mention anything about your actual problem - if you want to have Python code for your created classes, you can invert the thing, and introspect yur generated classes to write a proper .py file that does the same as the programatic call did in first place.

On the other hand, if you want the source code for the lines containing the type call, that is feasible - but you will have to customize the class creation to the point of having the file and line number information on the code object used to create the class. Calling type does not use a code object to startwith - but there are ways to do it, although complicated. A while back I answered a question about if it was possible to make a programatically declared class to be indistinguishable from a normal, declared class - and I dig real deep into it - that answer will show all the meta-attributes that are used in the normal way, some of which you'd have to fill in - or worse - forge to create a programatic class which creation call can be pinpointed by getsource :

Detect if class was defined declarative or functional - possible?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM