


The Use of The ** Operator With Python and FastAPI Pydantic Classes
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.
The above is the detailed content of The Use of The ** Operator With Python and FastAPI Pydantic Classes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
