Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use vs. over use of *args in Python

I've been looking at the source code for an open source package that I'm using. Nearly every function uses *args instead of named arguments. I'm finding it hard to follow and use the code, because every time I want to call a function I have to go back, pick through the source code, and identify what the arguments should be, and what order they should be in. The question I have is this: Is there a compelling reason to use *args in every function, or is this an abuse of the concept? Thanks, -b

like image 231
brentlance Avatar asked Sep 19 '12 23:09

brentlance


3 Answers

This might be a personal reasoning but I only use *args and **kwargs when I have a lot of optional fields where some fields are only used in a certain context.

The only other occasion I used args is when I was building an XML RPC client for a cloud API. Since I was just passing parameters to an underlying layer and since the function where generated dynamically, I had no other choices but to use *args as I had no way to know all the parameters in advance.

In most case, you won't even need it. I consider it to be mostly laziness than anything else.

Some people who comes from Java and C# might use this as a replacement for "params", but there are so many way to pass optional parameters in python.

And I agree that even if you use *args, you should have a very good documentation.

like image 110
Samy Arous Avatar answered Nov 09 '22 16:11

Samy Arous


Using *args in every function is a bad idea because it can mask errors in your code (calling a function with the wrong number of arguments). I suppose the rule of thumb should be to only use *args if you need *args.

like image 32
mgilson Avatar answered Nov 09 '22 18:11

mgilson


In the Zen of Python, we are told to prefer explicit over implicit. Explicit arguments should be used whenever possible.

like image 3
Mark Ransom Avatar answered Nov 09 '22 17:11

Mark Ransom