6

I've encountered a problem in a project where it may be useful to be able to pass a large number (in the tens, not the hundreds) of arguments to a single "Write once, use many times" function in Python. The issue is, I'm not really sure what the best ay is to handle a large block of functions like that - just pass them all in as a single dictionary and unpack that dictionary inside the function, or is there a more efficient/pythonic way of achieving the same effect.

Fomite
  • 2,213
  • 7
  • 30
  • 46
  • 1
    Check out http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python, which can be used for this. Similar to unpacking a dictionary, but each function just unpacks the arguments it is looking for – colcarroll Feb 10 '14 at 16:05
  • Could you post your code, please? – kkuilla Feb 10 '14 at 16:06
  • @kkuilla No, because this is a 'decide on a method before I write the code' kind of situation. – Fomite Feb 10 '14 at 16:27
  • I could imagine that could be off-topic (primarily opinion-based). Anyway, I think @JLLagrange's link and the ones within that post will take you quite far... – kkuilla Feb 10 '14 at 17:28

1 Answers1

0

Depending on exactly what you are doing, you can pass in arbitrary parameters to Python functions in one of two standard ways. The first is to pass them as a tuple (i.e. based on location in the function call). The second is to pass them as key-value pairs, stored in a map in the function definition. If you wanted to be able to differentiate the arguments using keys, you would call the function using arguments of the form key=value and retrieve them from a map parameter (declared with ** prefix) in the function definition. This parameter is normally called kwargs by convention. The other way to pass an arbitrary number of parameters is to pass them as a tuple. Python will wrap the arguments in a tuple automatically if you declare it with the * prefix. This parameter is usually called args by convention. You can of course use both of these in some combination along with other named arguments as desired.

HackerBoss
  • 829
  • 7
  • 16