Home / Function/ decimal_encoder() — fastapi Function Reference

decimal_encoder() — fastapi Function Reference

Architecture documentation for the decimal_encoder() function in encoders.py from the fastapi codebase.

Entity Profile

Dependency Diagram

graph TD
  35e48d24_ce6f_6204_5c5c_4cc89decc2b9["decimal_encoder()"]
  ea747667_035c_8539_a8f7_f347fb7e7c39["encoders.py"]
  35e48d24_ce6f_6204_5c5c_4cc89decc2b9 -->|defined in| ea747667_035c_8539_a8f7_f347fb7e7c39
  style 35e48d24_ce6f_6204_5c5c_4cc89decc2b9 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

fastapi/encoders.py lines 42–64

def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
    """
    Encodes a Decimal as int if there's no exponent, otherwise float

    This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
    where an integer (but not int typed) is used. Encoding this as a float
    results in failed round-tripping between encode and parse.
    Our Id type is a prime example of this.

    >>> decimal_encoder(Decimal("1.0"))
    1.0

    >>> decimal_encoder(Decimal("1"))
    1

    >>> decimal_encoder(Decimal("NaN"))
    nan
    """
    exponent = dec_value.as_tuple().exponent
    if isinstance(exponent, int) and exponent >= 0:
        return int(dec_value)
    else:
        return float(dec_value)

Domain

Subdomains

Defined In

Frequently Asked Questions

What does decimal_encoder() do?
decimal_encoder() is a function in the fastapi codebase, defined in fastapi/encoders.py.
Where is decimal_encoder() defined?
decimal_encoder() is defined in fastapi/encoders.py at line 42.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free