3

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?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
latj
  • 616
  • 1
  • 6
  • 23

1 Answers1

0

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?

jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • 1
    I have a large number of text files that describe class names and attributes. I want to generate the class definition boilerplate, setters/getters and put them into files. From there they can be edited. I know I can use templating like jinjia2 and caveman this. I just want to see if I could find a more clever way; maybe not. – latj Jan 20 '20 at 21:58
  • 1
    So you really want to render readable Python for the class specs you have laying in text files. I think jinja2 or other templating,combined with introspection, if you want to create the actuall class objects, can work nicely. – jsbueno Jan 20 '20 at 22:02