On-demand function sharing [closed]
I need to convert from strings to the code named references. The only currently known option is a script that makes a script, and I was thinking it could be inline like exec
.
class finder:
def __init__(self, parent):
self.parent = parent
def isin(self, what):
return what in self.parent
def find(self, what):
if self.isin(what): return self.parent.__dict__[what.__name__]
else: return __import__("pull").__dict__["downloader"](self.parent.hosts).download(what)
def put(self, what):
f = self.find(what)
self.parent.__dict__[f.__name__] = f
from sock import Socket
from unpack import unpacker
...
class downloader:
def __init__(self, hosts):
self.hosts = hosts
def download(name):
for host in hosts:
pack = unpacker()
s = Socket(host[0], host[1])
s.send("get " + name)
f = pack.unpack(s)
if f is not None: return f
I may be wrong, but I think what you're looking for is the ability to find the symbol for a method or attribute based on a string that is determined at runtime. If that's the case, I would pursue a different approach than a strategy based around exec
or eval
which have problems, like potential python injection attacks and tricky debugging...
In python everything is an object, including modules, classes and methods. How this helps you is that a module, let's call it spam
may have a method, let's call it eggs
you can access the eggs
method by it's name like this:
spam.__dict__['eggs']
Now you may be asking "But how do I find the spam
module by it's name?" This can done by importing the module by name using __import__
:
spam = __import__('spam')
So, to call the eggs
method with no arguments:
s = __import__('spam')
e = s.__dict__['eggs']
e()
Try eval
>>> a = 'hi'
>>> b = 'a'
>>> eval(b)
'hi'
精彩评论