0

Let's say I have something like:

source_string = """
class someClass:
   def __init__(self):
       self.s = "some String"
   def _return_s(self):
       return self.s

 """

Can I turn this string into a module-like object? To help you understand better:

SomeClassModule = _import(source_string)
print(SomeClassModule.someClass()._return_s())

If this is possible my goal is to make an import system that uses URLs.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user3103366
  • 65
  • 1
  • 9

1 Answers1

0

Using exec, you can do this as has been pointed out. Try it out:

>>> source_string = """
... class someClass:
...    def __init__(self):
...        self.s = "some String"
...    def _return_s(self):
...        return self.s
... 
...  """
>>> exec(source_string)
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'ask', 'random', 'someClass', 'source_string', 'var']
>>> x = someClass()
>>> x
<__main__.someClass object at 0x7f131424a1d0>
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_return_s', 's']
>>> x.s
'some String'
>>> x._return_s()
'some String'

I don't understand why you want to do this. Why can't you just define the classes normally?

joel goldstick
  • 4,393
  • 6
  • 30
  • 46
  • I know I can use exec but it doesn't do what I need, I could make it do what I need but that's a bit hacky. I needed something that returns the string of code like an import. But I don't think that is possible out of the box. The reason I wanted to do this is because I wanted to import stuff via url. For example, `module = _import("http://example.com/modules/mod.py")` – user3103366 Jun 12 '16 at 21:46
  • Oh, I think I understand. – joel goldstick Jun 12 '16 at 21:50
  • You should make a class that contains all the other classes, then simply return it. – Uncle Dino Jun 12 '16 at 22:47