I want to create python functions on the go, with the following template:
def x(sender,data):
r=b''
r+=sender.send_type0(data[0])
r+=sender.send_type1(data[1])
r+=sender.send_type2(data[2])
...
r+=sender.send_typen(data[n])
return r
I want to create many of those functions from an array which holds type data as a 2D array. I can generate simple functions at runtime, but there I would like to run a for-statement only at the generation, and not at every call of the function. How can I achieve this?
Asav Patel
1,1821 gold badge8 silver badges25 bronze badges
asked Dec 22, 2016 at 2:00
Uncle Dino
8641 gold badge7 silver badges23 bronze badges
1 Answer 1
You could use getattr to dynamically type out the attribute...
def x(sender,data):
return b"".join(
getattr(sender, "send_type"+i)(data[i])
for i in xrange(len(data))
)
I don't think you're going to find much of a performance advantage in having the function precompiled, assuming that is even possible...
answered Dec 22, 2016 at 2:04
Shadow
9,5474 gold badges50 silver badges60 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Uncle Dino
So there's no fancy solution to do what I want. I' disappointed in Python... :D
Shadow
What language actually supports this out of interest? And what advantage does it have over my solution of just doing it dynamically?
lang-py
sender? How can a byte string become a function? I'm not following your example.