See the previous installment in this series to catch up with Python functions with default arguments.
Python functions with variable length arguments
Let’s consider a scenario where we as developers aren’t sure about how many arguments a user will want to pass while calling a python function. For example, a function that takes floats or integers (irrespective of how many they are) as arguments and returns the sum of all of them. We can implement this scenario as shown below:
“””Sum all values in the *args.”””
# Initialize result to 0
result = 0
# Sum all values
for i in args:
result += i
# Return the result
The flexible argument is written as
* followed by the parameter name in the Python function definition. The parameter
args preceded by
* denotes that this parameter is of variable length. Python then unpacks it to a tuple of the same name
args which will be available to use within the function. In the above example, we initialize the variable
result to 0 which will hold the sum of all arguments. We then loop over the
args to compute a sum and update the
result with each iteration. Finally, we return the sum to the calling statement. The
sum_all python function can be called with any number of arguments and it will add them all up as follows:
# Calling the sum_all function with arbitrary number of arguments.
print(sum_all(1, 2, 3, 4, 5))
# Calling with different numbers of arguments.
print(sum_all(15, 20, 6))
*args is used as the parameter name (the shorthand for arguments), but we can use any valid identifier as the parameter name. It justs needs to be preceded by
* to make it flexible in length. On the same lines, Python provides another flavor of flexible arguments which are preceded by double asterisk marks. When used ,they are unpacked to dictionaries (with the same name) by the interpreter and are available to use within the function. For example:
“””Print out key-value pairs in **kwargs.”””
# Run for loop to prints dictionary items
for key, value in kwargs.items():
print(key + ‘: ‘ + value)
Here, the parameter
**kwargs are known as keywords arguments which will be converted into a dictionary of the same name. We then loop over it and print all keys and values. Again, it is totally valid to use an identifier other than
kwargs as the parameter name. The
info python function can be called as follows:
# Calling the function
print(info(ticker=’AAPL’, price=’146.83′, name=’Apple Inc.’, country=’US’))
name: Apple Inc.
That is all about the default and flexible arguments.
In the next installment, the author will discuss documentation string, DocStrings.
Visit https://www.quantinsti.com/ for ready-to-use Python functions as applied in trading and data analysis.
Disclosure: Interactive Brokers
Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.
This material is from QuantInsti and is being posted with permission from QuantInsti. The views expressed in this material are solely those of the author and/or QuantInsti and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.
In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.
Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.