Consider this class supplied as a string (not in a file and I can't put it in a file):
cstr = """
class A:
def show(self, msg):
print "msg:", msg
"""
I seek to compile and execute this as follows (in pseudopython). Note that the actual class name A
is not important -- only that it contain the method show()
which I will call. Yes, a robust example would do getattr
and check for callable and all but here's the gist:
clazz = compile(cstr)
instance = clazz()
instance.show("hello")
There's plenty of material out there on import
and importlib
taking strings to files and paths but not direct strings as inputs.
I explored using StringIO
to create a file-like object that could be passed to import
but there doesn't seem to be an import from stream facility either.
This question was marked as a possible dupe but the reference to the other question, like most, deals with class definitions that already exist in the code and are already compiled in and then instantiated by name e.g. 'A'. Imagine an interactive GUI with a window to input a class def in python. I capture that as a string. Now what?