Python function with many arguments

I am new to Python and a higher level in general, so I was wondering if he looked at it if I have a function that takes a lot of arguments and how best to archive my code to prevent this.

For example, this function essentially prints each location of a line in a file.

def scan(fpin,base,string,pNo,print_to_file,dumpfile_path,quiet): 

This function is called from the main function, which basically analyzes the command line arguments and passes data to the scan function. I was thinking of creating a class containing all of these arguments and passing it for scanning, but there would be only one instance of this data, so that would not be pointless?

+6
source share
2 answers

Named arguments are your friends. For things that act as semi-optional configuration options with reasonable defaults, set the default options and pass them (as named arguments) for situations other than the default. If there are many parameters without reasonable defaults, you can name them all when calling the function.

Consider the built-in sorted function. It takes up to four arguments. Is the reverse parameter before or after cmp ? What should I pass as key if I want the default to be executed? Answer: Damn if I remember. I call sorted(A, reverse=True) and it does what I expect.

By the way, if I had tons of "config" arguments that I passed to each scan call and changed each time (say, fpin and string ), I could lean all the other arguments in the dictionary and then pass it to the function with syntax **kwargs . This is a bit more advanced. See the manual for more details. (Note that this is NOT the same as declaring a function as accepting **kwargs . The definition of a function is the same, the only difference is that the calls to it are similar.)

+6
source

No, there is nothing wrong with that. If you have N different arguments (things that control the execution of your function), you should somehow pass them - how you actually do this, just user preferences, if you ask me.

However ... if you find yourself doing something like this:

 func('somestring', a=A, b=B, c=C) func('something else', a=A, b=B) func('something third', a=A, c=C, d=D) 

etc .. where A, B, C are really configurations for many different things, then you should start learning the class. A class does a lot of things, but it also creates a context. Instead, you can do something like:

 cf = myclass(a=A, b=B, c=C, d=D) cf.func('somestring') cf.func('something else') cf.func('something third') 

and etc.

+1
source

All Articles