-2

I trying to create functions by gitting functions names from giving dictionary, actually, I'm not sure if this is possible, her is what I'm trying to do:

def functions_factory(my_dict):
        for the name in my_dict:
            create_function(name)

def   create_function(function_name):
        x=0
        # **code implentation:** here should write a code that can create function with name = <function_name>
ALiAuto
  • 15
  • 6
  • 2
    creating variables (in this case functions) like this is never a good idea and a sign that you should take a different approach to your problem. This seems like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. – Ma0 Mar 05 '18 at 08:40
  • Likely a duplicate of https://stackoverflow.com/q/3687682/831878 -- but yeah, it's unlikely this is really the right way to go about things. Definitely seems like an XY. – Ray Toal Mar 05 '18 at 08:41
  • How would you generate the *body* of the function in a dynamic way? Using a dynamic name for the function seems like the lesser problem compared to the fact that its code will always be the same. As such, this seems very pointless. – deceze Mar 05 '18 at 08:46
  • it's very good idea for people who can think out of the box. if you know an answer, add it, if you don't, please leave without philosophizing. – ALiAuto Mar 06 '18 at 08:09

1 Answers1

0

Try this

one = 'one'
two = 'two'
three = 'three'
l = {one:1, two:2, three:3}
def some_stuff():
    print("some stuff")
for keys,item in l.items():
    def _f():
        some_stuff()
    globals()[keys] = _f
    del _f

one()
two()
three()

output:

some stuff

some stuff

some stuff

Community
  • 1
  • 1
Artier
  • 1,648
  • 2
  • 8
  • 22