Is it possible to do something like this:
def fns(Names, Args, Bodies):
for i in range(len(Names)):
exec("def " + Names[i] + "(" + Args + "): " + Bodies[i])
All functions should be in the global scope, amount of calling code should not depend on number of functions.
asked Apr 13, 2012 at 5:49
DSblizzard
4,1697 gold badges52 silver badges78 bronze badges
-
6Why would you need to do this?Blender– Blender2012年04月13日 05:50:31 +00:00Commented Apr 13, 2012 at 5:50
-
I want to quickly create getters and setters for data structures made from lists. Specific fns() code doesn't matter much, it's about idea.DSblizzard– DSblizzard2012年04月13日 05:52:26 +00:00Commented Apr 13, 2012 at 5:52
-
3As others note, there is definitely a better way to do this. Creating global getters and setters for a data structure isn't the right choice in an OOC language anyway- just create a class.David Robinson– David Robinson2012年04月13日 06:17:03 +00:00Commented Apr 13, 2012 at 6:17
-
There are several ways you could do this, but it depends on exactly what you're trying to acheive? Can you give a complete example, showing examples of Names, Args and Bodies? Off the top of my head, one way you could do this would be mess around with code objects, but there's probably a simpler and better way.aquavitae– aquavitae2012年04月13日 06:39:22 +00:00Commented Apr 13, 2012 at 6:39
1 Answer 1
not a good idea.. however
for i in range(len(Names)):
exec("def " + Names[i] + "(" + Args + "): " + Bodies[i]) #create locally
globals()[Names[i]] = locals()[Names[i]] #assign to global space
but I wouldn't recommend doing this... and that's untested code
answered Apr 13, 2012 at 5:54
Joran Beasley
114k13 gold badges168 silver badges187 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
jamylak
Do you mean uppercase
names? Also you are assigning globals()[Names[i]] to a string i think.DSblizzard
Yes: "TypeError: 'str' object is not callable"
jamylak
change it to
globals()[Names[i]] = locals()[Names[i]]. Also I don't think you should be doing this as well, it is very hack-ish...Joran Beasley
oops will fix now (should be locals()names[i]) ..... also I second @jamylak's opinion
Joran Beasley
make a generic function maybe or a subclass of list that has the getters and setters you want... theres not very many good reasons I can think of for dynamic code like what your talking about...
|
lang-py