亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1. Initial issues and challenges
2. Solution: _missing_ method
3. Implement the _missing_ method
4. Use and verification
5. Precautions and best practices
Summarize
Home Backend Development Python Tutorial Python Enum Flexible Input Handling: A Deeper Understanding of the _missing_ Method

Python Enum Flexible Input Handling: A Deeper Understanding of the _missing_ Method

Oct 16, 2025 am 09:36 AM

Python Enum Flexible Input Handling: A Deeper Understanding of the _missing_ Method

This article details how to handle diverse input values ??elegantly by overriding the _missing_ class method in the Python enum.Enum class. Even if the internal value of an enumeration member is fixed, we can make it accept multiple external representations (such as "true", "yes", etc.) and map it to the correct enumeration member while keeping the original internal value unchanged, thereby improving the robustness and user-friendliness of the enumeration.

In Python development, enum.Enum provides a powerful way to define a collection of constants. However, in practical applications, we often face a challenge: how to allow enumerations to accept multiple forms of input and uniformly map them to specific enumeration members while keeping the internal values ??of the enumeration members themselves unchanged. For example, an enumeration representing "yes/no" may have its internal values ??defined as "Y" and "N", but when receiving external input, it may need to recognize multiple forms such as "true", "yes" or even "T" as the meaning of "yes".

This article will use a specific case to introduce in detail how to use the _missing_ class method of enum.Enum to solve this problem and achieve flexible input processing.

1. Initial issues and challenges

Suppose we define a YesOrNo enumeration to represent "yes" or "no":

 import enum

class YesOrNo(enum.Enum):
  YES = "Y"
  NO = "N"

We hope that when the external input is "Y" or "N", the corresponding enumeration member can be created directly. For example, YesOrNo("Y") can get YesOrNo.YES. This part of the functionality is supported by enum.Enum by default.

However, what if our system needs to accept a wider range of inputs, such as "true" or "false", and map them to YesOrNo.YES and YesOrNo.NO, while requiring YesOrNo.YES.value to still be "Y" and YesOrNo.NO.value to still be "N". Trying YesOrNo("true") directly will throw a ValueError because "true" is not among the values ??of YES or NO.

An intuitive but undesirable approach is to modify the enumeration definition:

 # Modification is not recommended because it will change the internal value of the enumeration class YesOrNo(enum.Enum):
  YES = "true"
  NO = "false"

Although this modification will make YesOrNo("true") work, YesOrNo.YES.value will become "true" instead of "Y" as we expect, which conflicts with our need to keep the internal value unchanged.

2. Solution: _missing_ method

enum.Enum provides a special class method called _missing_, designed to handle situations when the value passed into the enumeration constructor cannot directly match any enumeration member. By overriding this method, we can implement custom lookup logic to map non-standard input to the correct enumeration members.

The signature of a _missing_ method is usually _missing_(cls, value), where cls is the enumeration class itself and value is the unmatched value that was passed into the constructor. The method needs to return the corresponding enumeration member and should allow default behavior (throw ValueError) or explicitly throw an exception if a match cannot be found.

3. Implement the _missing_ method

Here is the complete implementation using the _missing_ method to solve the above problem:

 import enum

class YesOrNo(enum.Enum):
    YES = "Y"
    NO = "N"

    @classmethod
    def _missing_(cls, value):
        """
        This method is called when the value passed in does not directly match any enumeration member.
        It attempts to map various forms of input to YES or NO enumeration members.
        """
        # Convert input value to lowercase for case-insensitive comparison normalized_value = str(value).lower()

        if normalized_value in ('y', 'yes', 'true', 't'):
            return cls.YES
        elif normalized_value in ('n', 'no', 'false', 'f'):
            return cls.NO

        # Make Enum throw ValueError by default if no known form is matched
        # Or you can customize other exceptions to be thrown # raise ValueError(f"'{value}' is not a valid YesOrNo value.")

Code analysis:

  1. @classmethod decorator : _missing_ must be a class method because it operates on the enumeration class itself, not an instance.
  2. cls parameter : represents the YesOrNo enumeration class. Enumeration members can be accessed through cls.YES and cls.NO.
  3. value parameter : This is the value passed into the YesOrNo() constructor but does not directly match any member, for example "true".
  4. normalized_value = str(value).lower() : To make the matching logic more robust, we convert the input value to a string and lowercase it. This can handle input with different cases such as "True" and "YES".
  5. Conditional judgment :
    • If normalized_value belongs to any of ('y', 'yes', 'true', 't'), return cls.YES.
    • If normalized_value is any of ('n', 'no', 'false', 'f'), return cls.NO.
  6. Missing match handling : If the _missing_ method does not find a match internally and returns an enumeration member, then enum.Enum will throw ValueError by default. In the example, we do not throw explicitly but rely on this default behavior. If you need more specific error information, you can raise ValueError(...) manually.

4. Use and verification

Now, we can test this enhanced YesOrNo enumeration:

 # Test various inputs print(f"YesOrNo('Y'): {YesOrNo('Y')}")
print(f"YesOrNo('y'): {YesOrNo('y')}")
print(f"YesOrNo('YES'): {YesOrNo('YES')}")
print(f"YesOrNo('true'): {YesOrNo('true')}")
print(f"YesOrNo('T'): {YesOrNo('T')}")
print(f"YesOrNo('N'): {YesOrNo('N')}")
print(f"YesOrNo('false'): {YesOrNo('false')}")
print(f"YesOrNo('no'): {YesOrNo('no')}")

# Verify that the internal values ??of the enumeration members remain unchanged print(f"YesOrNo.YES.value: {YesOrNo.YES.value}")
print(f"YesOrNo.NO.value: {YesOrNo.NO.value}")

# Try invalid input try:
    YesOrNo("unknown")
except ValueError as e:
    print(f"Error for 'unknown': {e}")

Output example:

 YesOrNo('Y'): YesOrNo.YES
YesOrNo('y'): YesOrNo.YES
YesOrNo('YES'): YesOrNo.YES
YesOrNo('true'): YesOrNo.YES
YesOrNo('T'): YesOrNo.YES
YesOrNo('N'): YesOrNo.NO
YesOrNo('false'): YesOrNo.NO
YesOrNo('no'): YesOrNo.NO
YesOrNo.YES.value: Y
YesOrNo.NO.value: N
Error for 'unknown': 'unknown' is not a valid YesOrNo

It can be seen from the output that whether it is "true", "yes" or "Y", it is successfully mapped to YesOrNo.YES. Meanwhile, YesOrNo.YES.value is still "Y", which meets all our needs.

5. Precautions and best practices

  • _missing_ is only called when there is no direct match : if the value passed in can directly match the value of an enumeration member, the _missing_ method will not be called. For example, YesOrNo("Y") will directly return YesOrNo.YES.
  • Return type : The _missing_ method must return an enumeration member (that is, in the form cls.MEMBER), otherwise a type error will be thrown.
  • Exception handling : It should allow enum.Enum to throw a ValueError if the _missing_ does not recognize the passed-in value, or a more specific exception based on the business logic. Do not return None or other values ??that are not members of the enumeration.
  • Performance considerations : For very large enumerations or high-frequency calling scenarios, the logic in _missing_ should be as efficient as possible. If the mapping relationship is complex, consider using a dictionary for precomputation or caching.
  • Type conversion : Within _missing_, it is generally recommended to convert the value to a uniform type (such as string) and normalize it (such as .lower()) to handle diverse inputs.
  • Documentation note : When defining an enumeration containing a _missing_ method, it is recommended that the input types and mapping rules it handles be clearly stated in the class or method docstring so that other developers can understand and use it.

Summarize

By overriding the _missing_ class method of enum.Enum, we gain a powerful tool that can flexibly handle and map diverse input values ??without changing the internal values ??of the enumeration. This greatly enhances the robustness and user-friendliness of enumerations, allowing our code to better adapt to changes in external input, while maintaining the consistency and clarity of the internal data model. The _missing_ method is undoubtedly a solution worth considering when designing enumerations that need to handle multiple forms of input.

The above is the detailed content of Python Enum Flexible Input Handling: A Deeper Understanding of the _missing_ Method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Efficient merge strategy of PEFT LoRA adapter and base model Efficient merge strategy of PEFT LoRA adapter and base model Sep 19, 2025 pm 05:12 PM

This tutorial details how to efficiently merge the PEFT LoRA adapter with the base model to generate a completely independent model. The article points out that it is wrong to directly use transformers.AutoModel to load the adapter and manually merge the weights, and provides the correct process to use the merge_and_unload method in the peft library. In addition, the tutorial also emphasizes the importance of dealing with word segmenters and discusses PEFT version compatibility issues and solutions.

How to install packages from a requirements.txt file in Python How to install packages from a requirements.txt file in Python Sep 18, 2025 am 04:24 AM

Run pipinstall-rrequirements.txt to install the dependency package. It is recommended to create and activate the virtual environment first to avoid conflicts, ensure that the file path is correct and that the pip has been updated, and use options such as --no-deps or --user to adjust the installation behavior if necessary.

How to test Python code with pytest How to test Python code with pytest Sep 20, 2025 am 12:35 AM

Python is a simple and powerful testing tool in Python. After installation, test files are automatically discovered according to naming rules. Write a function starting with test_ for assertion testing, use @pytest.fixture to create reusable test data, verify exceptions through pytest.raises, supports running specified tests and multiple command line options, and improves testing efficiency.

How to handle command line arguments in Python How to handle command line arguments in Python Sep 21, 2025 am 03:49 AM

Theargparsemoduleistherecommendedwaytohandlecommand-lineargumentsinPython,providingrobustparsing,typevalidation,helpmessages,anderrorhandling;usesys.argvforsimplecasesrequiringminimalsetup.

Floating point number accuracy problem in Python and its high-precision calculation scheme Floating point number accuracy problem in Python and its high-precision calculation scheme Sep 19, 2025 pm 05:57 PM

This article aims to explore the common problem of insufficient calculation accuracy of floating point numbers in Python and NumPy, and explains that its root cause lies in the representation limitation of standard 64-bit floating point numbers. For computing scenarios that require higher accuracy, the article will introduce and compare the usage methods, features and applicable scenarios of high-precision mathematical libraries such as mpmath, SymPy and gmpy to help readers choose the right tools to solve complex accuracy needs.

How to correctly merge PEFT LoRA adapter with basic model How to correctly merge PEFT LoRA adapter with basic model Sep 17, 2025 pm 02:51 PM

This article details how to use the merge_and_unload function of the PEFT library to efficiently and accurately merge the LoRA adapter into the basic large language model, thereby creating a brand new model with integrated fine-tuning knowledge. The article corrects common misunderstandings about loading adapters and manually merging model weights through transformers.AutoModel, and provides complete code examples including model merging, word segmenter processing, and professional guidance on solving potential version compatibility issues to ensure smooth merge processes.

How to work with PDF files in Python How to work with PDF files in Python Sep 20, 2025 am 04:44 AM

PyPDF2, pdfplumber and FPDF are the core libraries for Python to process PDF. Use PyPDF2 to perform text extraction, merging, splitting and encryption, such as reading the page through PdfReader and calling extract_text() to get content; pdfplumber is more suitable for retaining layout text extraction and table recognition, and supports extract_tables() to accurately capture table data; FPDF (recommended fpdf2) is used to generate PDF, and documents are built and output through add_page(), set_font() and cell(). When merging PDFs, PdfWriter's append() method can integrate multiple files

How can you create a context manager using the @contextmanager decorator in Python? How can you create a context manager using the @contextmanager decorator in Python? Sep 20, 2025 am 04:50 AM

Import@contextmanagerfromcontextlibanddefineageneratorfunctionthatyieldsexactlyonce,wherecodebeforeyieldactsasenterandcodeafteryield(preferablyinfinally)actsas__exit__.2.Usethefunctioninawithstatement,wheretheyieldedvalueisaccessibleviaas,andthesetup

See all articles