How to not specify default parameters in python?
I'm working with a python package (MySQLdb). The connect method has lots of positional parameters, most of which have defaults, but some aren't easy to deduce.
How can I only specify the parameters I want?
i.e. if a connect method has the following signature:
connect(username, password, socket, timeout)
and socket
has a default value which may be system-dependent
is it possible to invoke it with something like the following so I don't over开发者_如何学编程write the default value for socket
:
connect('tom', 'passwd12', , 3)
Try this:
connect(username='tom', password='passwd12', timeout=3)
For more information please see Using Optional and Named Arguments.
It's better to use keyword arguments rather than positional parameters in this case. As is obvious
connect ('tom', 'passwd12, None, 3)
is a lot less understandable than
connect (username = 'tom',
password = 'passwd12',
timeout = 3)
the MySQLdb-python source says this about connect:
"It is strongly recommended that you only use keyword parameters."
精彩评论