FelixTheC / strongtyping

Decorator which checks whether the function is called with the correct type of parameters.
https://pypi.org/project/strongtyping/
107 stars 3 forks source link

Are there errors for undefined keys? #129

Closed yupix closed 9 months ago

yupix commented 9 months ago

First of all, thank you for creating such a useful library.

Is it possible to return an exception for undefined keys? As an example, if I pass a dict to User with a key age that I have not defined, it will return an exception.

The reason I want this feature is to help find things that are not defined in the TypedDict. It would be nice to be able to log warnings, etc. even if they are not exceptions.

from typing import TypedDict

from strongtyping.strong_typing import match_class_typing

@match_class_typing
class User(TypedDict):.
    id: str
    username: str
    description: str | None

User({"id": "0123", "username": "test", "description": None, "age": 10})

Due to my inexperience with English, I am using DeepL. I apologize if you find anything offensive.

FelixTheC commented 9 months ago

@yupix Thank you for using DeepL for easier communication.

The current behavior is that you won't get any exceptions if you have an undefined key inside your dictionary. This behavior should be supported. I will fill in a new issue/feature request for it. I'm thinking about something like.

@match_class_typing(throw_on_undefined=True)
class User(TypedDict):
    id: str
    username: str
    description: str | None

or

@match_class_typing
class User(TypedDict):
    id: str
    username: str
    description: str | None

    def throw_on_undefined(self):
        return True

what did you say to the solution ideas??

yupix commented 9 months ago

Thanks for the quick reply. I think the first code is better in my opinion.


class User(TypedDict):
   id: str
   username: str
   description: str | None
FelixTheC commented 9 months ago

Could you please tell me which Python version you're using? I plan to put this feature in the latest version which requires Python 3.12.

I will then extend the decorator to support throw_on_undefined

this will be the TestCase:

def test_undefined_keys_raise_error():

    @match_class_typing(throw_on_undefined=True)
    class User(TypedDict):
        id: str
        username: str
        description: str | None

    with pytest.raises(UndefinedKey):
        User({"id": "0123", "username": "test", "description": None, "age": 10})

    assert User({"id": "0123", "username": "test", "description": None})
yupix commented 9 months ago

The project I am creating is currently using Python 3.11 and will change to 3.12 on January 2 next year, three months after the release of 3.12. Therefore, it would be helpful if you could implement this project in Python 3.11 if possible.

As for the testing, I think it is good.

FelixTheC commented 9 months ago

feature is now available at https://pypi.org/project/strongtyping/3.12.1/