"TypedDict" In Python Is Actually AWESOME!
TypedDict in Python is actually awesome! In this video I will cover quickly how you can use it in your projects.
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels
00:00 Intro
00:28 Using TypedDict
02:13 NotRequired
03:11 Problem
03:39 TypedDict alternative version
04:42 Required
06:36 Deprecated in 3.11
07:01 Printing the TypedDict
07:20 Summing it up
Пікірлер: 76
i love the way you pronounce “category”, very unique haha
@kamurashev
Жыл бұрын
I read it as …you pronounce category and unique. I listened the whole thing one more time to find out how does he pronounces “unique” and then I get back to this comment and actually read it correctly, so now I am laughing.
@man0utoftime
Жыл бұрын
"ka-'TEG-o-ree" is a 1st for me, as well. 😂
@EverythingTechTime
11 ай бұрын
Cet egery
@tribaltalker1608
11 ай бұрын
I had a student who pronounced "integer" as "in tee grr". He had never heard anyone say the word, so he guessed the pronunciation from reading it. English doesn't have much consistency in how we spell words as we have (mostly) spurned the accent marks that other languages use. It's a linguistic minefield.
@herrpez
4 ай бұрын
@@tribaltalker1608 It's been quite a while since English spelling and pronunciation drifted apart. But once upon a time they were actually fairly close. Add the fact that English is basically three languages in a trench coat... 😂 It's no wonder people get confused.
I really enjoy learning from your video compilations. Thanks so much for the good work. Keep them coming through.
Nice feature. I’m definitely going to try it out in next project. And I like your style of these videos, keep up the good work 🙂
Ooh this is quite similar to c++'s 'typedef struct' declaration. It's super useful in data management for vectors and matrices.
Hell yeah! I had no idea this was possible! I've been missing this feature for ever since I started using typescript. Having an interface for a simple data type like a dictionary is the best!
Great video. Useful info and clearly explained. Thanks! (One small thing: the word 'category' has emphasis on the first syllable: CATegory).
Thanks for the info! I feel like this will make OOP easier to a certain extent.
This is not Python that I know 😂 This channel teached me a lot. Thank you so much
I dont see why I would use this over creating a dataclass of some sort
Hello! Is it not against the idea of a dictionary to specify in advance the keys and their types? Python also has namedtuples that should be way more efficient in use, especially given that one needs to declare types in advance, so obviously one needs to know them in advance. Is there a version of namedtuples where one can specify types?
Emm This will definitely help to organise more the codes, thanks for the tip
please make a video about class methods and object methods(all kind of it ) and the differences between them just for clarification (and also usage of them in real situations) because the way you teach is amazing and thank you very much for your consideration
@Indently
Жыл бұрын
I already did
What version of python3 is this? The "typing" package seems to change between sub-versions. For example, I would have thought you would use Optional and didn't even know NotRequired existed.
it seems very interesting to do 😀💯💙✨
I luv TypedDict, I had a long json body and keys were long I have to go back and forth to copy and paste that key. once I created the TypedDict the auto complete feels like magic ✨. unfortunately i had to use python 3.7 in prod so I had to install typing-extensions module to use TypedDict.
Love your content! not sure if it's intentional but your channel logo is so similar to LinkedIn I keep thinking it's a video posted by them fyi...
Thank you
What code editor are you using? it looks very nice
@SalticHash
11 ай бұрын
Seams to be pycharm
Thanks I learnt sth new
thanks for sharing. I tried this code: ====== from typing import TypedDict class Person(TypedDict): name: str age: int salary: float person: Person = { 'weight':125, 'height': '6ft', } print(person) ======= ... {'weight': 125, 'height': '6ft'} it worked fine and nothing stops me from giving anything I want to the 'person' dictionary. am I missing something here or I just don't get it?
Whoa. Bracket in Python!
Awesome. Although you didn't demostrate the use of reserved keywords since for != 'for', in != 'in' Nonetheless, Awesome tutorial
how and where to use this dictionaries?
@Indently
Жыл бұрын
They're just normal dictionaries, you use them exactly the same way you'd use other dictionaries.
you realLY love typing :D , why would you even consider that the first coordinate = {...} has anything to do with that class Coordinate?
from typing import TypedDict, NotRequired class Coordinate(TypedDict): # inheritance x: float y: float label: str category: NotRequired[str] # could be excluded / type needed # IDE helps with type: Coordinate coordinate: Coordinate = {"x":10, "y":10, 'label':"Profit", 'category':"Finance"} coordinated: Coordinate = {"x":15, "y":25, 'label':"Expenses"} # category not used. 6:40 from typing import TypedDict, NotRequired, Required Vote = TypedDict('Vote', {"for":int, "against":int}, total=False) # override for Votes = TypedDict('Votes', {"for":int, "against":Required[int]}, total=False) # type needed vote : Vote = {"for":100, "against":250} votes : Votes = {"against": 450}
I'm now wondering when to use TypedDict vs @dataclass
@walker-gx1lx
Жыл бұрын
same here...
@Skull0
Жыл бұрын
If you want your data structure to behave like a dict but with a typed schema to prevent error this is the solution, you'll have all the expected methods and behavior or a normal dict which differ from a object, even if the typing is only statically checked this is a good solution to that need. Otherwise you'll have to create a class that derives from dict and then add validation to ensure all parameters are of the right type, it will execute at runtime so add overload which may not be necessary compare to just let the developer know that the a parameter type is wrong at development time with static analysis.
Good day greetings
great video. It seems that python is chasing statically typed languages in this regard. Better to keep to core, simple, readable python...
I receive - ImportError: cannot import name 'NotRequired' from 'typing'. Python 3.9.5
@DrDeuteron
Жыл бұрын
ikr, a version minimum would be nice. I can't get the latest thanks to the security ppl.
Why use this instead of a @dataclass?
@YatharthMathur
Жыл бұрын
Because dataclasses aren't an exact replacement of python native dictionaries. TypedDict is just a type that helps with IDE auto completion. It's not adding any additional functionality like dataclasses.
@user-vt9bp2ei1w
Жыл бұрын
If you can implement your resource initialization yourself, then dataclass will indeed be better. But in most cases you will get data from other libraries, and these data structures are usually very "dirty". For example, processing from files (toml, json, xlsx), http/database responses, etc. are almost all nested dictionaries/lists. Converting these things into dataclasses will be cumbersome, creating a lot of dependencies and prone to errors .
What's the advantage of TypedDict vs dataclass?
@Alister222222
Жыл бұрын
I am also wondering this. I guess one advantage might be that a Dict is (?) smaller and more lightweight than a class, since classes are kind of extended Dicts with a lot of extra functionality.
@blackdereker4023
Жыл бұрын
@@Alister222222 I would put that under premature optimization. Unless you are creating hundreds of thousands of data or running Python on a microship you really shouldn't worry about that.
@spaghettiking653
11 ай бұрын
@@Alister222222 What would be the difference with a slotted class, for example, memory-wise? If you make use of slots, I believe that dramatically shrinks the possible values, because the class no longer wraps a dictionary, but rather has distinct fields for the properties, exactly like the intended use of TypedDict?
Please note that this is a bad use of TypedDict. The reason to use TypedDict is to adapt code that's already depending on untyped dictionaries to use types. Perhaps to add a type structure to the result of json.load(). However, designing your structured code from the ground up around dictionaries is a bad idea, because the purpose of a dict is to be unstructured. For designing strucutred types, Python has a dedicated mechanism: Classes. In particular, the dataclass from the dataclasses module. These are designed to have a structure, and are generally more convenient to use that way (for example, because they support looking up attributes with object.field instead of object["field"] out of the box).
@keithkaranu4258
Жыл бұрын
Not: I'm not a python guy so idk if this is a good practice in Python, but I can imagine this being useful for implementing algebraic data types sort of like interfaces in typescript.
@SkyyySi
Жыл бұрын
@@keithkaranu4258 I don't see how using a dictionary with a fixed type structure would change the things you can model over a class
I seem to not have Required and NotRequired in typing module. I'm using PyCharm
@grippnault
11 ай бұрын
For me, I do not have Required and NotRequired. My version of Python (3.10.5) would only except Optional
@Indently
11 ай бұрын
You’re right, it’s new as of Python 3.11
@grippnault
11 ай бұрын
@@Indently Thank you for replying.
One really annoying thing about TypedDict is that you can't inherit from a TypedDict and then change the type of the values already defined For example, this does not work: class A(TypedDict): x: int Class B(A): x: str
for was not acceptable in class but "for" is acceptable in class - for is reserved, not "for"
So what language does the world pick for a lingua franca? English! hahahaha Want to know why? Because of the Industrial Revolution, and also the airline industry, and movies, and TV, and on and on. Moral of the story: you don't have to always be "right", you just have to be persistent and gain the leading edge. Don't ever give up.
So, a feature was introduced in 3.8, deprecated in 3.11 and to be removed in 3.13? Seriously? Is Python only for kids playing around?
Please Hindi subtitle
@spaghettiking653
11 ай бұрын
Sir I do not speak Hindi but you can try automatic subtitles and automatically translate to Hindi
kategari? 😂
pydantic with less abilities
English is a messed-up language ... "caaaaah-tegory'
> Invent a dynamically typed language for quick-and-dirty scripting and glueing > Decide you need static types and end up with a language as messy as Ruby and as cumbersome as Java, except 90x slower > mUh eCoSyStEm
@DrDeuteron
Жыл бұрын
quick and not dirty. This fixation on typing is anti-pythonic.
@K9Megahertz
11 ай бұрын
This is why I just stick with C/C++. If you're going to write code, why use an interpreted language that's orders of magnitude slower than something else. In either case you're going to be writing a lot of code, so why gas up and drive a Pinto when you can do it with a Ferrari... Every program boils down to a few core concepts: loops, lists, arrays, variables, conditional statements, etc.. The part I don't understand is all these languages come out that try to be better/safer than C++ and then they just slowly all regress back towards C++.
@DrDeuteron
11 ай бұрын
@@K9Megahertz You are bastardizing Greenspuns 10th Law
@spaghettiking653
11 ай бұрын
@@DrDeuteron I disagree, why not use types when your functions are required to take a specific type of data? Obviously some functions don't do this, e.g. print can print anything, but what about a function that iterates the lines of a file? Obviously it needs to take a file(-like) object, so why not type it as such? Then it's more obvious what the code does. And why not annotate what the function returns, because then you can tell without having to read the code? It's just easier, not to mention that the code editor can help you when it knows the possible types.
@DrDeuteron
11 ай бұрын
Sentinel pattern: iter(fp.readline, “”) Is sufficient
What a crap