


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> 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") </class>
Output
<class> dict_items([('name', 'Stephen'), ('age', 30), ('profession', 'Software Developer')]) name: Stephen age: 30 profession: Software Developer </class>
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!

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
