The alternative syntax for TypedDicts is mainly useful if you have a TypedDict with a key containing special characters like period (ex: "http.method"). The alternative syntax can also be useful on older versions of Python 3.x (
Glad I could be of help! It's so damn useful honestly -- I need to get round to creating loads of these as Python 3.7 compatibility becomes less of an issue
This does seem genuinely useful. But as many others have mentioned i can't really see the benefit over Pydantic. It feels like you are making a class which serves as a factory for a dict, but have to couple this waaaay to much, even the keys have to match the class attributes. Why not have a "as/to_dict" method of the class which defines the typing, then you just construct a class and represent it as a dict which is supported with even dataclasses. The keys of the dict are attributes of the class, so you don't have to type as much and it has the same result + lower coupling. I'm not bashing this feature though, i would be joyed to have someone tell me when to use this over pydantic/dataclasses (basically structs lol). I'm guessing it has to do with mutability and/or resources but i'm not a computer scientist so i have no idea what is "really" going on under the hood in both cases.
Is it possible that when using "total=false", the default assumtion of Required vs NotRequired is simply flipped? so usually all fields are Required and you mark the ones that aren't, but now every field is NotRequired and you mark the ones that are? Also, is there a way with this syntax to allow adding arbitrary keys additionally to the predefined and typed ones?
Ya know, that's probably it. The total kwarg reverses it normally, so that makes sense -- why didn't I think of that! As for arbitrary keys, I'm not sure. You'd have to look that one up.
_Ugh,_ why don't we just start a superset called TypePython (TyPython? Typton?!) and be done with it, _jeeeeeeeeeeeez_ Not sure if I'm even joking there... Thank You for the video!
You don't understand the point. Scripting is scripting, don't mess with strongly type. I didn't like the idea declare type everywhere, if that the case, why not jump into strongly type language like Java or c# that are more performant than scripting. This is just tool, you use it when it needed. Superset js with typescript just create new mess, divergent code and make type code more than it should be. Scripting should easy to write.
@@muharief3885 I didn't like it either when I started. Now I understand it's basically a necessity for large scale projects to remain reliable and maintainable. Typescript is great compared to JS, it's not perfect but it's far from being the mess that JS itself is. Now, Python is not nearly as bad as JS and doesn't really need a TS equivalent but having an *optional* feature for mandatory type declaration/expectation, even if it's non-strict and only throws warnings, would be absolutely amazing. Even for simple data analysis usecases this would save you so much headaches of having to constantly check the type of everything.
I think I've been using TypedDicts wrong this whole time. I've always thought that to use them, you had to use them as a constructor, e.g., ProfileT(name="John", age=35). At that point, you might as well just use a dataclass (which I still think I prefer over TypedDicts). This makes TypedDicts actually useful, though!
You can create TypedDicts either way. The main advantage TypedDicts have over dataclasses is that they serialize to/from JSON trivially, since a TypedDict is just a dict.
I've seen T suffix mostly used for TypeVar, and never seen it used with regular types or even type aliases. TypedDict can be used as a regular dict, so it doesn't make much sense to use T in its name from my perspective.
Hi there, thanks for sharing! I don't quite understand it, I tried the following code and it works fine .... : ----------------------- from typing import TypedDict class ProfileT(TypedDict): name: str age: int jobs: list[str]
profile: ProfileT = { "name":"Ethan", "age":24, "jobs":["se"], "gender":"male", } profile["age"] = '20' print(profile) --------------------------- nothing stopped the code from running good. it printed out : {'name': 'Ethan', 'age': '20', 'jobs': ['se'], 'gender': 'male'} Am I missing something here or I just didn't get it ? Thanks!
The only validation is at the type-checking level, so something like Mypy would pick up errors. At runtime, they're seen as normal dicts. If you want runtime validation, you need something like Pydantic (latest video) or Msgspec (next week's video).
You can also mix required and non required keys by creating two classes and inheriting one from the other. From your example it would look like this; from typing import TypedDict class ProfileReqFields(TypedDict): name: str age: int class ProfileT(ProfileReqFields, total=False): jobs: list[str] profile: ProfileT = { "name": "Ethan", "age": 24, "jobs": ["Software Engineer"], }
But what is the advantage of this as opposed to just using a regular class? You could also just use a dataclass for exactly this thing, right? Why a TypedDict?
I believe TypedDicts are lighter weight. And if you're only using it to type dictionaries, you wouldn't need to create a dataclass for it. That's how I understand it anyways.
Lighter weight is ridiculous in Python which is slow as hell anyway. The real reason for TypedDict I think is that you can still use it where you need dicts, **kwargs etc. However, a typed dictionary where not all keys, and all values are same type may be considered bad practice better replaced by a data class. From an architecture point of view. I fear TypedDict does not handle the case where a key type is mapped to value type, or does it?
This mirrors functionality in typescript to type is dicts. I guess there are a few reasons 1. You want them to be dicts as they are used in other classes 2. You are retrofitting this to existing code and you don’t want to rewrite a lot of code
@@nassehk the : in the type definition introduced by Python 3.6. Like "count : int = 3", here the type is that class (it's compatible with dictionary definition)
@@jphvnet Thanks yeah I see it now. What confused me is seeing the type definition out of the function definition. I had not seen type definition being used like that.
The alternative syntax for TypedDicts is mainly useful if you have a TypedDict with a key containing special characters like period (ex: "http.method"). The alternative syntax can also be useful on older versions of Python 3.x (
Ah okay, that makes sense. Thanks for mentioning!
This is wonderful, I have *so* many applications that would benefit from this
Glad I could be of help! It's so damn useful honestly -- I need to get round to creating loads of these as Python 3.7 compatibility becomes less of an issue
Just found you out yesterday and you already helped me improve my codes so much. Much appreciated!
Glad I could help!
Great to know that python supports better typing. One question i have is, at what point do you need to swap out typing for pydantic?
please keep creating these amazing content:)))
This does seem genuinely useful. But as many others have mentioned i can't really see the benefit over Pydantic. It feels like you are making a class which serves as a factory for a dict, but have to couple this waaaay to much, even the keys have to match the class attributes. Why not have a "as/to_dict" method of the class which defines the typing, then you just construct a class and represent it as a dict which is supported with even dataclasses.
The keys of the dict are attributes of the class, so you don't have to type as much and it has the same result + lower coupling. I'm not bashing this feature though, i would be joyed to have someone tell me when to use this over pydantic/dataclasses (basically structs lol). I'm guessing it has to do with mutability and/or resources but i'm not a computer scientist so i have no idea what is "really" going on under the hood in both cases.
Glad to hear that you're finding TypedDict useful! (I helped bring it to life.)
Wow, never thought I'd get a comment from any of the authors of these features! Thanks for stopping by!
Excellent content, my friend..!!
The google algorithm brought me here...
You have a new subscriber
Thank you so much!
Is it possible that when using "total=false", the default assumtion of Required vs NotRequired is simply flipped? so usually all fields are Required and you mark the ones that aren't, but now every field is NotRequired and you mark the ones that are?
Also, is there a way with this syntax to allow adding arbitrary keys additionally to the predefined and typed ones?
Ya know, that's probably it. The total kwarg reverses it normally, so that makes sense -- why didn't I think of that!
As for arbitrary keys, I'm not sure. You'd have to look that one up.
What about using pydantic?
Could you maybe consider upping the font size please? My old eyes struggle on a mobile screen.
this was really helpful, thanks 😀
Very useful for serverless apps and creating types for events (also it supports generic overloading)
Very underrated channel
Thanks a ton 🙏, your videos are awesome!
super clear and useful! Subscribed.
Glad you liked it, and thanks for the support! (:
nice to see python getting similar to Typescript xD
_Ugh,_ why don't we just start a superset called TypePython (TyPython? Typton?!) and be done with it, _jeeeeeeeeeeeez_
Not sure if I'm even joking there... Thank You for the video!
London Typton, sounds nice
You don't understand the point. Scripting is scripting, don't mess with strongly type. I didn't like the idea declare type everywhere, if that the case, why not jump into strongly type language like Java or c# that are more performant than scripting. This is just tool, you use it when it needed.
Superset js with typescript just create new mess, divergent code and make type code more than it should be. Scripting should easy to write.
@@muharief3885 I didn't like it either when I started. Now I understand it's basically a necessity for large scale projects to remain reliable and maintainable. Typescript is great compared to JS, it's not perfect but it's far from being the mess that JS itself is. Now, Python is not nearly as bad as JS and doesn't really need a TS equivalent but having an *optional* feature for mandatory type declaration/expectation, even if it's non-strict and only throws warnings, would be absolutely amazing. Even for simple data analysis usecases this would save you so much headaches of having to constantly check the type of everything.
I think I've been using TypedDicts wrong this whole time. I've always thought that to use them, you had to use them as a constructor, e.g., ProfileT(name="John", age=35). At that point, you might as well just use a dataclass (which I still think I prefer over TypedDicts). This makes TypedDicts actually useful, though!
You can create TypedDicts either way. The main advantage TypedDicts have over dataclasses is that they serialize to/from JSON trivially, since a TypedDict is just a dict.
My senior says there's no advantage on using TypedDict and it's much better to use dataclasses, pydantic or attrs
Except, you are required to pass a dict or kwargs …
@@falklumo yes, the source will often untyped like eg. json, but you can put it directly into typed data structure
Nice
I've seen T suffix mostly used for TypeVar, and never seen it used with regular types or even type aliases. TypedDict can be used as a regular dict, so it doesn't make much sense to use T in its name from my perspective.
I've never given it much thought tbh, but yeah, I think you're right.
Hi there, thanks for sharing! I don't quite understand it, I tried the following code and it works fine .... :
-----------------------
from typing import TypedDict
class ProfileT(TypedDict):
name: str
age: int
jobs: list[str]
profile: ProfileT = {
"name":"Ethan",
"age":24,
"jobs":["se"],
"gender":"male",
}
profile["age"] = '20'
print(profile)
---------------------------
nothing stopped the code from running good. it printed out : {'name': 'Ethan', 'age': '20', 'jobs': ['se'], 'gender': 'male'}
Am I missing something here or I just didn't get it ?
Thanks!
The only validation is at the type-checking level, so something like Mypy would pick up errors. At runtime, they're seen as normal dicts. If you want runtime validation, you need something like Pydantic (latest video) or Msgspec (next week's video).
You can also mix required and non required keys by creating two classes and inheriting one from the other. From your example it would look like this;
from typing import TypedDict
class ProfileReqFields(TypedDict):
name: str
age: int
class ProfileT(ProfileReqFields, total=False):
jobs: list[str]
profile: ProfileT = {
"name": "Ethan",
"age": 24,
"jobs": ["Software Engineer"],
}
But what is the advantage of this as opposed to just using a regular class? You could also just use a dataclass for exactly this thing, right? Why a TypedDict?
I believe TypedDicts are lighter weight. And if you're only using it to type dictionaries, you wouldn't need to create a dataclass for it. That's how I understand it anyways.
Lighter weight is ridiculous in Python which is slow as hell anyway. The real reason for TypedDict I think is that you can still use it where you need dicts, **kwargs etc.
However, a typed dictionary where not all keys, and all values are same type may be considered bad practice better replaced by a data class. From an architecture point of view. I fear TypedDict does not handle the case where a key type is mapped to value type, or does it?
This mirrors functionality in typescript to type is dicts.
I guess there are a few reasons
1. You want them to be dicts as they are used in other classes
2. You are retrofitting this to existing code and you don’t want to rewrite a lot of code
YOOOOOO I DIDN'T KNWO ABOUT THIS
Nice but I would just use a data class or take it one step further with pydantic
Shouldn't this also work with dataclasses from the standard library?
You mean making the TypedDict a dataclass? I honestly don't know if that's a thing you can do.
gender = Mail, which kind tho?
PLEASE ZOOM IN PLEASE
Feel like this is just extra unnecessary code. Not saying its useless but i think theres better methods.
What is that syntax in line 10?
Timestamp?
@@jphvnet1:36
@@nassehk the : in the type definition introduced by Python 3.6. Like "count : int = 3", here the type is that class (it's compatible with dictionary definition)
@@jphvnet Thanks yeah I see it now. What confused me is seeing the type definition out of the function definition. I had not seen type definition being used like that.
First hehe