The Use of The ** Operator With Python and FastAPI Pydantic Classes

王林
发布: 2024-08-31 12:32:12
原创
714 人浏览过

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 anexponentiation operator. However in this article we will be looking at another context which it is used. We will be looking at its use as anunpacking 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:  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

 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 Use of The ** Operator With Python and FastAPI Pydantic Classes的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!