0

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?

1
  • 1
    Can you give more details. What type is sender? How can a byte string become a function? I'm not following your example. Commented Dec 22, 2016 at 2:11

1 Answer 1

2

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...

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

2 Comments

So there's no fancy solution to do what I want. I' disappointed in Python... :D
What language actually supports this out of interest? And what advantage does it have over my solution of just doing it dynamically?

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.