The **
operator in Python is contextual or dependent on what it is used with; when used with numbers(typically between two numbers), it serves as an exponentiation operator. However in this article we will be looking at another context which it is used. We will be looking at its use as an unpacking operator, used to unpack Python dictionaries.
Anyone who has coded in Python must have seen **kwargs
. Short for keyword arguments. They are arguments passed to functions in a key = value
syntax. kwargs
is used when we do not know the number of keyword arguments that will be passed into our function. **kwargs
is a dictionary type and is as good as passing a dictionary into a function. This dictionary contains:
- Keys corresponding to the argument names.
- Values corresponding to the argument values.
Going by this logic, in this article, we will be looking at its use cases in Python building up to its use case in FastAPI with Pydantic classes.
The following points will be looked at.
- Use with Python functions.
- Use with Python classes.
- Use with FastAPI Pydantic classes.
- Benefits of use.
Note: It is not compulsory to use kwargs, you can use any other naming convention e.g.
**myArgs
,**anything
etc.
Prerequisites
- Knowledge of Python classes and functions.
- Some basic knowledge of FastAPI.
Use with Python Functions
In this example, we will have a number of keyword arguments passed to a function as **kwargs
and since **kwargs
is a dictionary, we will use the dictionary method .items()
on it. The .items()
method returns a view object that displays a list of the dictionary's key-value
tuple pairs.
def print_details(**kwargs):
# kwargs is a dictionary containing all keyword arguments
print(type(kwargs)) # Output: <class 'dict'>
print(kwargs.items()) # Displays the dictionary items (key-value pairs)
# Iterate over the key-value pairs in kwargs
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function with multiple keyword arguments
print_details(name="Stephen", age=30, profession="Software Developer")
Output
<class 'dict'>
dict_items([('name', 'Stephen'), ('age', 30), ('profession', 'Software Developer')])
name: Stephen
age: 30
profession: Software Developer
Use with Python Classes
As we must have noticed, Python classes are callable; this means that we can call a class the same way we call a function. Calling a class creates an instance (an object) of that class.
class Tech:
def __init__(self, dev, devops, design):
self.dev = dev
self.devops = devops
self.design = design
# Call class to create an instance
tech = Tech(dev, devops, design)
Calling Tech
with argument values will return the instance tech
.
In classes, the **
operator unpacks the dictionary allowing each key-value pair to be passed as a named argument to the class constructor.
In the example for this section, we define a class. We define a dictionary with properties matching the class parameters. We then create an instance of the class, using the **
to unpack the dictionary.
class Tech:
def __init__(self, dev, devops, design):
self.dev = dev
self.devops = devops
self.design = design
# Define a dictionary with properties matching the class's parameters
tech_team = {
'dev': 'Stephen',
'devops': ['Jenny', 'Rakeem', 'Stanley'],
'design': 'Carlos'
}
# Create an instance of the class using ** to unpack the dictionary
tech = Tech(**tech_team)
print(tech.dev)
print(tech.devops)
print(tech.design)
The above code is equivalent to:
class Tech:
def __init__(self, dev, devops, design):
self.dev = dev
self.devops = devops
self.design = design
# Define a dictionary with properties matching the class's parameters
tech_team = {
'dev': 'Stephen',
'devops': ['Jenny', 'Rakeem', 'Stanley'],
'design': 'Carlos'
}
# Create an instance of the class
tech = Tech(
dev = tech_team["dev"],
devops = tech_team["devops"],
design = tech_team["design"]
)
print(tech.dev)
print(tech.devops)
print(tech.design)
This is because:
tech = Tech(**Tech_team)
Is same as:
tech = Tech(
dev = tech_team["dev"],
devops = tech_team["devops"],
design = tech_team["design"]
)
Use with FastAPI Pydantic Classes
Pydantic is a Python library used for data validation, it is even touted as the most widely used data validation library for Python, by using Python3's type hinting system. This Pydantic employed in FastAPI helps us define data models which in simple terms are classes.
In our classes, we can specify types for our attributes or fields e.g str, int, float, List. When data is provided, Pydantic checks to make sure it matches.
In addition to this Pydantic helps with parsing and serialization. Serialization is the process of transmiting data objects into an easily transmissible format; for instance an object or array into JSON format for its simplicity and ease of parsing.
Pydantic has a BaseModel
class which classes defined inherit from. Below is an example of a Pydantic model:
from pydantic import BaseModel, EmailStr
# We import the BaseModel and Emailstr type from Pydantic
class UserInDB(BaseModel):
username: str
hashed_password: str
email: EmailStr
full_name: Union[str, None] = None
Suppose we have:
class Item(BaseModel):
name:str
price:float
app = FastAPI()
@app.post("/items/")
async def create_item(item:Item):
return item
In the code above, item
which is the request body parameter, is an instance of the Item
model. It is used to validate and serialize the incoming JSON request body to ensure it matches the structure defined in th Item model.
Pydantic's .dict()
Method
Pydantic models have a .dict()
method which returns a dictionary with the model's data.
If we create a pydantic model instance:
item = Item(name="sample item", price=5.99)
Then we call dict()
with it:
itemDict = item.dict()
print(itemDict)
We now have a dictionary and our output will be:
{
"name": "sample item",
"price":5.99
}
Note that:
Item(name="sample item", price=5.99)
Is equivalent to
# Using the unpacking operator
Item(**itemDict)
# Or
Item(
name=itemDict["name"], price=itemDict["price"
)
Benefits of Use
We will now look at some situations where using the unpacking operator is beneficial.
- Creating new dictionaries from a pre-existing dictionary by adding or modifying entries.
original_dict = {"name": "Stephen", "age": 30, "profession": "Software Developer"}
# Creating a new dictionary with additional or modified entries
new_dict = {**original_dict, "age": 31, "location": "New York"}
print(new_dict)
- Joining dictionaries into one. With the unpacking operator we can merge multiple dictionaries.
default_config = {"theme": "light", "notifications": True}
user_config = {"theme": "dark"}
# Merging dictionaries using unpacking
final_config = {**default_config, **user_config}
print(final_config)
- Handling of arguments in functions in a dynamic manner. This can be seen in our early examples.
Conclusion
The dictionary unpacking operator **
is one to consider using because of its dynamic nature of handling arguments in functions and classes, and in merging and creation of new dictionaries. All these put together leads to lesser code and better maintenance of code.
Top comments (0)