π Dynamic Behavior in Python
Contents
π Dynamic Behavior in Python#
Python includes a lot of flexibility and can adjust DataTypes and behaviors based on valid operations on inputs provided.
*args#
Sometimes when you build functions you do not know how many inputs you will have. This can be handled usings *args.
Note
Any *variable can be used for *args, it is convention and good practice to use *argsdef add(*args):
print(sum(args), type(args))
add(2, 3)
5 <class 'tuple'>
**kwargs#
Sometimes you want to input an arbitrary number of key-value pairs. This can be done with the **kwargs input.
Note
Any **variable can be used for **kwargs, it is convention and good practice to use *kwargsdef add(**kwargs):
print(kwargs) # this is a dictionary
print(sum(kwargs.values()))
add(two=2, three=3)
{'two': 2, 'three': 3}
5
*args and **kwargs#
You can use predefined inputs, *args, and **kwargs together. Python will choose the right input.
def add(text, *args, **kwargs):
print(text + f"kwargs is: {sum(kwargs.values())}")
print(text + f"args is: {sum(args)}")
add("the sum is:", two=2, three=3)
the sum is:kwargs is: 5
the sum is:args is: 0
add("the sum is:", 2, 3)
the sum is:kwargs is: 0
the sum is:args is: 5
add("the sum is:", 2, 100, three=3, _1k=1000)
the sum is:kwargs is: 1003
the sum is:args is: 102
Note
*args and **kwargs are much more useful with iterators which you will learn about soon.Dynamic Typing#
Within functions it is possible to input different DataTypes as inputs and as long a python can infer a valid operation and DataType it will automatically adjust
def multiplier(x, y):
print(f"multiplier ({x}, {y}) is {x * y}")
print(type(x * y))
multiplier(3, 2)
multiplier (3, 2) is 6
<class 'int'>
multiplier(3.14, 2)
multiplier (3.14, 2) is 6.28
<class 'float'>
multiplier("Drexel Dragons ", 3)
multiplier (Drexel Dragons , 3) is Drexel Dragons Drexel Dragons Drexel Dragons
<class 'str'>