lundi 20 janvier 2020

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?





Aucun commentaire:

Enregistrer un commentaire