I apologize if this question has already been asked/answered, I would have expected that to be the case but was unable to find any related questions...
I'd like to create a python function that takes two mandatory arguments, one named argument, and some unknown number of other, non-named arguments as so:
def my_function(arg1, arg2, arg3=None, *other_args):
pass
Is this possible in Python 2.x?
Can a function accept named arguments in addition to a variable length argument list?
I believe the answer is 'no', in which case I'm thinking the only solution available to me would be something similar to the following:
def my_function(arg1, arg2, **kwargs):
arg3 = kwargs["arg3"]
other_args = kwargs["other_args"]
Is that correct?
That syntax is certainly valid, but I think you mean can you write the function signature such that arg3 is only bound if it's used as a named parameter (e.g. my_function(1, 2, arg3 = 3)), and otherwise to have all arguments past the first two be caught by *other_args, in which case the answer is no. Optional arguments can be specified by naming, but they're also positional like normal arguments and are filled in if enough parameters are available, before resorting to catch-alls like *args or **kwargs.
I would probably write it exactly as you did, using keyword arguments
Related
Is there a generic python way to pass arguments to arbitrary functions based on specified positions? While it would be straightforward to make a wrapper that allows positional argument passing, it would be incredibly tedious for me considering how frequently I find myself needing to pass arguments based on their position.
Some examples when such would be useful:
when using functools.partial, to partially set specific positional arguments
passing arguments with respect to a bijective argument sorting key, where 2 functions take the same type of arguments, but where their defined argument names are different
An alternative for me would be if I could have every function in my code automatically wrapped with a wrapper that enables positional argument passing. I know several ways this could be done, such as running my script through another script which modifies it, but before resorting to that I'd like to consider simpler pythonic solutions.
For key arguments use **kwargs but for positional arguments use *args.
Let's consider
foo(arg1=123, arg2=None) and foo(arg1=123).
Tell me please, if these two ways are equivalent ?
No, the two given function signatures (and hence functions) are not equivalent.
In foo(arg1=123, arg2=None), you have two arguments -- arg1 and arg2, which can be used inside the function as local names. Note that, assigning a value of None to some name does not make it anything special/different as far as the assignment statements are concerned. It is in fact a common way to give a placeholder value for a variable that is not mandatory or may be an empty mutable object.
On the other hand, foo(arg1=123) has only one argument arg1, which is available on the function's local scope for use.
Edit:
If you have a function defined as foo(arg1, arg2), both arguments are mandatory (positional) arguments.
So, foo(arg1=21) will throw a TypeError as you have not provided arg2. Whereas, foo(arg1=21, arg2=None) will work just fine as you have provided values for both the arguments.
Edit2:
If you have a function defined as foo(arg1=None, arg2=None) (or something similar i.e. with default values), both arguments are optional (keyword) arguments. In that case, both of the mentioned definitions would be the same.
I am a few days new to Python so if this is silly please excuse me..
Is there a method to sending multiple variables to a single function? As an example:
pe.plot_chart(conn,7760,'DataSource1',123,save=True)
This above function takes a connection to SQL where it pulls data for unique ID 7760 from datasource1 (uniqueid 123). Can I use some method to send multiple criteria for the DataSource1 field? e.g.
pe.plot_chart(conn,7760,['DataSource1','DataSource2'],[123,345],save=True)
pe.plot_chart was created by me, so any modifications that have to be made to it to make it work are fine
Is this type of operation possible to perform?
EDIT: Adding on some extra info.
The plot_chart function.. well it plots a chart, and saves it to the location above. Each call of the function produces one graph, I was hoping that by sending multiple values for a parameter I could have the function dynamically add more series to the plot.
So if I send 4 data sources to the function, I will end up with 4 lines on the plot. For this reason I am not sure looping through a data source collection would be good (will just produce 4 plots with one line?)
Yes you can send multiple arguments to a function in python, but that shouldn't be a surprise. What you cannot do is having positional arguments after a keyword argument, that is calls like f(1, foo=2, 3) is not allowed (your example is invalid for that reason).
Also you cannot supply multiple values to a single argument in a strict sense, but you can supply an list or tuple to a single argument, that is for example f(1, foo=(2, 3)) is acceptable and your function might interpret that as you are supplying two values to the foo argument (but in reality it's only one tuple).
The downside is that the function must be able to distinguish between a tuple as argument and what is intended as a single argument. The easiest way is to insist on that the argument should be a tuple or at least iterable. The function would have to look somewhat like:
def f(foo, bar):
for x in foo:
do_something(bar, x)
f(bar=fubar, foo=(arg1, arg2, arg3))
f((arg1, arg2, arg3), bar=fubar) # same as previous line
f((arg1, arg2, arg3), fubar) # same as previous line
another more advanced alternative would be to use keyword argument for everything except what would be the multiple arguments by using variable argument list, but this is somewhat clumpsy in python2 as you'll need to supply all arguments as positional unless you manually unpack the keywords arguments, in python3 there is some relief as you can force using of keyword arguments:
def f(*args, bar=fubar):
for x in args:
do_something(bar, x)
f(arg1, arg2, arg3, bar=fubar)
# f(fubar, arg1, arg2, arg3) is not allowed
and then every argument that is not a keyword argument (still those positional arguments has to be the first arguments) will end up in args, and the bar argument is required to be passed as keyword argument.
In python2 the above would need to be:
def f(*args, **kwds):
bar = kwds.get("bar", fubar)
for x in args:
do_something(bar, x)
data_sources = [data_source1, data_source2, data_source3]
for source in data_sources:
pe.plotchart(connection, uniqueid = 7760, source...)
There's various ways to approach this - if you want to send an iterable (like a list) to your function once and have the function iterate through them, you can do that. You can also call the function from a loop. If the other parameters are going to change for each iteration, look into "zip", which is useful for pairing data for looping.
It's possible to pair data source specifications with unique IDs in your case. Here is a simple approach with lists of tuples:
def myFunc(values):
for v in values:
print v[0], v[1]
myFunc([("hello", 1), ("world", 2)])
The list elements could also be expanded into classes if there is a need for more description for each line to plot. The benefit of this flip is that you are handling one list of line descriptors (which are represented by tuples), not loosely coupled "arguments".
The output BTW is this:
hello 1
world 2
Your specific case would change into this
pe.plot_chart(conn,7760,[('DataSource1',123),('DataSource2',345)],save=True)
I am a beginner in python programming and recently i came across functions,parameters,arguments and...
I have done a lot of research on Parameters and Arguments(Even checked the answers of similar past questions on StackOverflow)but i couldn't get their meanings.
Some say,parameters are variables which we give them to functions while we are defining them and arguments are values that are passed in function once we given them to the function in order to run the function.While some other say no,it's not like that.Parameters and Arguments are same and do the same task...
Can anyone tell me the meaning Parameters and Arguments in a clear way?
Are Parameters and Arguments considered variables?
For what kind of purpose do we use them?
Please don't explain too much complicated,i am a beginner.
Thank you so much.
Per the official documentation:
Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
def func(foo, bar=None, **kwargs):
pass
foo, bar and kwargs are parameters of func. However, when calling func, for example:
func(42, bar=314, extra=somevar)
the values 42, 314, and somevar are arguments.
The glossary defines them as:
Argument: A value passed to a function (or method) when calling the function.
Parameter: A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept.
Python doesn't really have "variables" like some other languages - it has "names" referring to "objects". See e.g. "Code like a Pythonista" and "Facts and myths about Python names and values".
Take it this way:
Parameter:
A parameter represents a value that the procedure expects you to pass when you call it. The procedure's declaration defines its parameters.
Argument:
An argument represents the value that you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure.
Example:
int add (int value1, int value2) // Here value1 and value2 are PARAMETERS.
{
return value1+value2;
}
Now while calling the function
answer = add(2,3); // Here values 2 and 3 are ARGUMENTS.
Same goes with Python, while declaration, they are parameters, while calling they are arguments.
Some may differ with what i have written, but this is how it is actually known in programming world.
I'm going through python and I was wondering what are the advantages of using the *args as a parameter over just passing a list as a parameter, besides aesthetics?
Generally it's used to either pass a list of arguments to a function that would normally take a fixed number of arguments, or in function definitions to allow a variable number of arguments to be passed in the style of normal arguments. For instance, the print() function uses varargs so that you can do things like print(a,b,c).
One example from a recent SO question: you can use it to pass a list of range() result lists to itertools.product() without having to know the length of the list-of-lists.
Sure, you could write every library function to look like this:
def libfunc1(arglist):
arg1 = arglist[1]
arg2 = arglist[2]
...
...but that defeats the point of having named positional argument variables, it's basically exactly what *args does for you, and it results in redundant braces/parens, since you'd have to call a function like this:
libfunc1([arg1val,arg2val,...])
...which looks very similar to...
libfunc1(arg1val,arg2val,...)
...except with unnecessary characters, as opposed to using *args.
That is for flexibility.
It allows you to pass on the arguments, without knowing how much you need. A typical example:
def f(some, args, here): # <- this function might accept a varying nb of args
...
def run_f(args, *f_args):
do_something(args)
# run f with whatever arguments were given:
f(*f_args)
Make sure to check out the ** keyword version.