cdgriffith / Box

Python dictionaries with advanced dot notation access

Home Page:https://github.com/cdgriffith/Box/wiki

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

add TypedDict equivalent support

ofbeaton opened this issue · comments

It would be great if I could use TypedDict (PEP 589) equivalent for my type definition of Box.

I'm very new to python, so perhaps there is already a way to do this... I searched the Box docs, several pages of issues here, and asked in #python (they recommended I just make my own dataclasses/attrs)

but this is example TypedDict code:

from typing import TypedDict

class Movie(TypedDict):
    name: str
    year: int

def my_func(movie : Movie):
   """do some stuff"""

how to convert this so def my_func(movie: Box) works while also preserving the TypedDict Movie check?

one workaround might be:

def my_func(movie: Movie):
  movie_box = Box(movie)
  """do some stuff"""

would this be too slow to always convert it? assume the calling function already has a box so would be converting to dict from a box, only to have it convert back to a box...

if I wanted to return a TypedDict I'd also have to convert my Box to a dict on return, only to have it reconverted back to a box.

These are just internal methods to my project, so I'm not worried about making the API require a Box, I thought it would save me having to convert them constantly, as I use Box everywhere.

As #python channel mentioned another alternative is to use dataclasses/attrs, but that seems to reinvent the wheel somewhat and brings me away from the convenience of Box and TypedDict's.

If there is already a way to do this, I humbly suggest a page on how to type Box's in the wiki docs be added. I hear basic typing of Box[str, Any] should work... but it is also not specifically documented.

Thanks for the great project!

If you want type hinting and validation, use msgspec or pydantic (or without validation: dataclass).