0

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.

4
  • 6
    Why would you need to do this? Commented 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. Commented Apr 13, 2012 at 5:52
  • 3
    As 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. Commented 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. Commented Apr 13, 2012 at 6:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

Do you mean uppercase names? Also you are assigning globals()[Names[i]] to a string i think.
Yes: "TypeError: 'str' object is not callable"
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...
oops will fix now (should be locals()names[i]) ..... also I second @jamylak's opinion
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...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.