0

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?

Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33
  • 1
    Possible duplicate of [Convert string to Python class object?](https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object) – Georgy Apr 20 '18 at 13:44
  • The result of executing that string will be a namespace containing a class definition. It will NOT magically give you the class itself, just because that's the only thing in the namespace; you have to explicitly look up the name `A` in the namespace, and call that in order to get your instance to call `.show()` on. – jasonharper Apr 20 '18 at 13:51
  • @jasonharper if I use the actual `compile(str, filename, mode)` function, it returns a type 'code' object which really doesn't do a lot; I don't think it has even been added to the namespace to look up. – Buzz Moschetti Apr 20 '18 at 14:05
  • `compile()` requires a bit of extra work to get the results into a callable form. `exec` is an easier way to do it, pass a dictionary as its global environment, and that's where you'll find your `A`. – jasonharper Apr 20 '18 at 16:00
  • Yep, `exec` looks like the best way. You should post it as an answer. – Buzz Moschetti Apr 23 '18 at 23:08

0 Answers0