Есть ли способ указать произвольные дополнения в Python TypedDict?Python

Программы на Python
Ответить Пред. темаСлед. тема
Гость
 Есть ли способ указать произвольные дополнения в Python TypedDict?

Сообщение Гость »


I would like to specify a TypedDict that specifies some fields and types, but also allows for having a "bag" of extra things that are allowed in the dict.

A concrete example of this would be for adding typing information to a decorator that would be used in conjunction with Flask (since, if I'm not mistaken, the flask route decorator passes the "path params" as keyword arguments. I would like to be able to access a kwarg, manipulate it, and pass it along.

My decorator might look more or less like this:

from typing import Any, Callable, ParamSpec, Tuple, TypedDict, TypeVar from myproject.models import Thing P0 = ParamSpec("P0") P1 = ParamSpec("P1") R = TypeVar("R") # I know these TypedDicts aren't valid, but hopefully they illustrate what I want. class IncomingKwargs(TypedDict): thing_id: str **rest class ForwardedKwargs(TypedDict): thing: Thing **rest Decoratee = Callable[P0, R] Decorated = Callable[P1, R] # Take the following with a grain of salt... def with_thing() -> Callable[[Decoratee], Decorated]: def decorator(f: Decoratee) -> Decorated: def wrapper(*args: Any, **kwargs: IncomingKwargs) -> R # Example manipulation. thing = Thing.from_id(kwargs["thing_id"]) return f(*args, thing=thing, **kwargs["rest"]) return wrapper return decorator # And then later, something Flasky like: @app.route("/things/:thing_id/frobnicate", method=["POST"]) @with_thing() def frobnicate_thing(thing: Thing) -> Tuple[str, int]: # Do stuff with the thing... return "Thing was frobnicated.", 200 I've looked at https://docs.python.org/3/library/typin ... .TypedDict and options like total=False don't seem like what I want, since I want the thing_id key to be required.

FWIW, I could probably achieve the typing I want in TypeScript like this:

type IncomingKwargs = { thing_id: str, [key: str]: any, } const someKwargs: IncomingKwargs = {thing_id: "12345", description: "A beautiful thing",} // Now `thing_id` is a string and `rest` is an object/dict of the other things. const { thing_id, ...rest } = someKwargs Things I've tried:
  • Reading docs, Python official and mypy - didn't find helpful examples
  • Subclassing my TypedDict class with one that inherits both the TypedDict and a regular dict - didn't "compile", nor gave me a way to pass along the "rest"
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Как указать общий тип для TypedDict?
    Anonymous » » в форуме Python
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • #Frida #Android - Есть ли способ прочитать произвольные аргументы собственного метода, перехваченного методом Intercepto
    Anonymous » » в форуме Android
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • Правильный способ документировать ключи в TypedDict?
    Anonymous » » в форуме Python
    0 Ответы
    2 Просмотры
    Последнее сообщение Anonymous
  • Как выполнить регрессию в Python, используя необычные или произвольные уравнения?
    Anonymous » » в форуме Python
    0 Ответы
    20 Просмотры
    Последнее сообщение Anonymous
  • Как уложить произвольные изображения в Python [закрыто]
    Anonymous » » в форуме Python
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»