Python: A Quick Guide To Type Annotations (ft. Mypy)

  Рет қаралды 35,835

Indently

Indently

Күн бұрын

Пікірлер: 97
@Indently
@Indently 9 ай бұрын
I apologise about the background static noise (if you're using headphones you'll notice it). My microphone fell apart earlier this week and I had to order some replacement parts, and as usual, anytime I even slightly modify the setup of my mic on my desk, it retaliates xD I'm fixing it now so it should be fine in the next video :)
@thepurplesmurf
@thepurplesmurf 9 ай бұрын
I just told the construction guys outside to stop using the jackhammer that I can hear if there is a background noise in your video. 😜
@Indently
@Indently 9 ай бұрын
I wish I could tell the construction workers outside my place the same thing :')
@logaspam
@logaspam 9 ай бұрын
I like that Python provides this stuff but doesn't insist on it. If I'm knocking up a quick script to do something once then it's unnecessary, but in bigger codebases or with multiple maintainers this can avoid a lot of problems.
@unlomtrash
@unlomtrash 9 ай бұрын
maybe you didn't mean it, but another argument in explicitly specifying the type for a variable may be the desire to indicate that this is its declaration, and not a re-assignment :)
@Indently
@Indently 9 ай бұрын
oooooooo, good point!
@wootdafuq2925
@wootdafuq2925 9 ай бұрын
When I started using some of your tips and tricks I have vastly improved my coding skills and that was also acknowledged by my senior colleagues. I now do it rarely without annotations and other stuff I have seen on your videos. Thanks for advancing my skills here ;)
@ultimateownsz
@ultimateownsz 9 ай бұрын
First I thought you had another collab, then I realized mypy wasn't a person 😅😂
@Nerdimo
@Nerdimo 9 ай бұрын
Type annotations were at first annoying for me, but once I realized they prevent me from making mistakes and give me different cases I might not have thought of, I’ve found them very helpful.
@Shivvorz
@Shivvorz 9 ай бұрын
The situation i find type annotations the most useful is using it in function signitures, it gives you type hints within the function body. This is especially good if some arguements are objects with complex class methods (usually provided by third party libraries). Btw it also coerces input arguements to the type you specify so you save some effort in dealing with edge cases
@christophhenninger6440
@christophhenninger6440 9 ай бұрын
For me, I use annotations all the time now. And I do it because it helps me think beforehand what the function is about. And it helps me afterwards, finding what I was thinking, too.
@qwarlockz8017
@qwarlockz8017 3 ай бұрын
This is so clear and well structured! Thank you. This is how all languages should be taught!
@CASnumber
@CASnumber 9 ай бұрын
I just solved a problem for my company using type annotations. Literally the tool I used to solve the issue
@johnmckown1267
@johnmckown1267 9 ай бұрын
Just for me personally, I prefer where the language itself mandates that all variables are explicitly typed. I like Python, and feel this type of video is valuable about how typing can be helpful.
@Me__Myself__and__I
@Me__Myself__and__I 9 ай бұрын
Agree 100%. Strongly typed code is less buggy, easier to read and easier to maintain.
@loverboykimi
@loverboykimi 9 ай бұрын
Man. you're writing very clean and smooth code. I get used to care these annotations by you. Many thanks.
@marcelpumpernickel
@marcelpumpernickel 9 ай бұрын
Regarding your section on the redundancy, I feel that it is only redundant because it's such a simple example. Instead, say you have some child classes to the class "Fruit"... Then this starts to make a lot more sense! Typing your variable as "Fruit" then shows that you can assign any of the child classes (e.g. Banana(), Apple(), etc.) to it while still maintaining functionality of the code. This also implies that you should only be using methods in the parent class Fruit when using that variable.
@Me__Myself__and__I
@Me__Myself__and__I 9 ай бұрын
Also it makes it clear that Fruit() is a constructor and not just a function call.
@Diegos79
@Diegos79 9 ай бұрын
Excellent as ever in all your precious videos! Thanks for your work. Please keep continue!
@ego-lay_atman-bay
@ego-lay_atman-bay 9 ай бұрын
I usually type everything, except things where I expect any type. Sometimes I don't type my variables, because my code editor sees what type the variables is, based off of it's initial value.
@angelhdzdev
@angelhdzdev 9 ай бұрын
from typings import Any
@Dunning_Kruger_Is__On_Youtube
@Dunning_Kruger_Is__On_Youtube 6 ай бұрын
Oh the joy of comments. At the end of the day, people should just do whatever they want to do and stop trying to tell someone else whose sharing their perspective what to do.
@RedShipsofSpainAgain
@RedShipsofSpainAgain 9 ай бұрын
3:25 I agree. That heuristic that pycharm uses of checking only if one element matches the type is really broken. It can't be that hard for a code editor to check that ALL weekends or a list match the type specified in the type annotation. PyCharm fail.
@MrStyles784
@MrStyles784 9 ай бұрын
Python allows lists containing multiple data types - it's not inherently incorrect. I suppose it could be made to enforce the annotations when present, but it would either require a more complicated annotation for lists containing more than one data type, or it would discourage the use of annotations for lists that are intended to have more than one data type
@Me__Myself__and__I
@Me__Myself__and__I 9 ай бұрын
Typed code is easier to read, thus easier to maintain and less buggy. The additional few seconds here and there pale in comparison to the time that can be saved due to those benefits. One additional bug due the wrong type being used can make up for the trivial amount of time it takes to include types on a whole lot of code. Personally I wish it was strongly typed and the Python compiler did care, but at least having type support and warnings in the IDE is better than nothing. P.S. Really good senior professional developers understand that considerations like readability, maintainability and consistency make for better code that saves significant time long-term. Only specifying types in some cases or for some projects makes your code inconsistent. Consistency has significant benefits.
@j4s0n39
@j4s0n39 6 ай бұрын
I'd love for python to have an option to enforce this, effectively becoming a strictly typed language. If they added options for that, for compiling all the code at runtime, like Perl does, to find code errors in every code path, and for preventing us from adding new members to class instances (which I've only done by typing in an incorrect variable name), python would be amazing.
@darcash1738
@darcash1738 9 ай бұрын
The type annotations for function params and return types is most useful to me and I use the inline ones like fruit: Fruit = Fruit() for my own classes like that. I guess the inline ones are most useful for more involved types like ones you made or something like list[str]. It gives you autofill if you do that which is nice. I don’t see the benefit of doing simple types like x: int = 11 tho.
@rethanon
@rethanon 9 ай бұрын
Good video, would just like to point out that some code editors are better than others in recognising type errors. For example, in VS Code using the example you provided elements: list[str] = [1, 2, 'a'] it highlights the list and gives the following error: "Expression of type "list[int | str]" cannot be assigned to declared type "list[str]" "Literal[1]" is incompatible with "str" "Literal[2]" is incompatible with "str" I do still use mypy to check my files though :) and I also use type annotations for everything.
@markchadwick77
@markchadwick77 9 ай бұрын
Thanks. I recently pondered this question myself (typing obvious assignments). It's good to see you came to this conclusion.
@eboyd53
@eboyd53 9 ай бұрын
Type annotations are great as they help you code with clarity. There's no guessing when you come back later to maintain or enhance the code.
@TomLeg
@TomLeg 7 ай бұрын
When you write a short bit of code to deal with a problem or question that needs to be handled immediately, you don't need typing or even classes, for your ten line program. But when you realize you're going to need to run that every week in a corn job, it's good to improve it to production standard.
@huckleberryfinn8795
@huckleberryfinn8795 8 ай бұрын
I LOVE type annotations in Python.
@falklumo
@falklumo 9 ай бұрын
Type annotations at the point of a variable initialization, as in fruit:Fruit=Fruit() are being phased out in strongly typed languages like Java. These now use type inference instead (even a new ‘var’ keyword). Maybe, Python should use type inference too, maybe with a missing actual type if it can be inferred. Because otherwise, it can get very clumsy with generic, optional etc types …
@alidev425
@alidev425 8 ай бұрын
like your coding style👍👍
@finnthirud
@finnthirud 9 ай бұрын
You're a great tutor! No cowboy coding culture here 🤠🐮
@voncolborn9437
@voncolborn9437 9 ай бұрын
I come for a long background of strongly typed languages "Ada, Modulo-2 , C/C++. The first time I sat down the first comment I had was , "where the hell are the type declarations?. How am I supposed to know what the intent is for this code?" the second thing was What? Indentation is part of the actual syntax? I cannot imagine trying to maintain a complicated library without at least using type hinting. Thanks for the video.
@Me__Myself__and__I
@Me__Myself__and__I 9 ай бұрын
Same. I really don't like that indentation has meaning. Reminds me of COBOL. Ick. How much time is saved by not having to put braces { } around code? Not enough.
@dustcore
@dustcore 8 күн бұрын
Thank you for explaining this. I was getting mad confused.
@ghrasko
@ghrasko 4 ай бұрын
Hi, many thanks for this video, I again learnt something and will definitelly follow. Even your "fruit: Fruit = Fruit()" is more than consistency. Se my example: dish1: Fruit = Fruit() dish2: Vegetable = Vegetable() dish3: Vegetable = Vegetable() dish4: Vegetable = dish2 dish5: Vegetable = dish1 # This will display a type checking error
@Whatthetrash
@Whatthetrash 9 ай бұрын
I just installed mypy. Thanks for the video! I'll see if it helps. :)
@cachamuertos
@cachamuertos 9 ай бұрын
I have a question. How can I declare a variable of certain class without defining its value. For example in c++ or Java you can declare it without value. But when I do it in python I have to use none, but then I would get tipyng warnings and also I can't reach the methods of it because it's a none variable instead of the class I want
@ego-lay_atman-bay
@ego-lay_atman-bay 9 ай бұрын
You can set the type to "Class | None", then just check if the variable is none before accessing the object properties.
@Jason-b9t
@Jason-b9t 9 ай бұрын
Use class-or-None or typing.Optional. e.g.: var: MyClass | None = None var2: typing.Optional[MyClass] = None python type hint is designed to be null-safe, None is not implicitly assumed to be a subclass of any class. note: > I can't reach the methods of it because it's a none variable instead of the class I want After using the if statement to narrow the type, the type hint will be able to prompt the method. e.g.: def func(var: int | None = None): print(var.bit_length()) # Pylance Warning: reportOptionalMemberAccess if not isinstance(var, int): raise TypeError('Variable var has incorrect type') print(var.bit_count()) # Pylance prompts methods without warning.
@anamoyeee
@anamoyeee 9 ай бұрын
"Type annotations don't stop your code from running" What if i annotate my variable with exit()
@angelhdzdev
@angelhdzdev 9 ай бұрын
😂
@huckleberryfinn8795
@huckleberryfinn8795 8 ай бұрын
Is there an extenstion like mypy for vscode?
@ismaelmerlo3730
@ismaelmerlo3730 8 ай бұрын
to me pycharm doesnt give me those warnings about wrong type, i installed mypy with pip and the plugin, but the plugin didnt work, so i have to ejecute mypy in the terminal. Im i missing a config of pycharm or smth? because it doesnt even tell me that im returning the wrong data type in a function when i specify it.
@gownerjones
@gownerjones 9 ай бұрын
Python is my favorite language but dynamic typing is an abomination
@rusektor
@rusektor 9 ай бұрын
"fruit: Fruit = Fruit()" is overkill, IMO. In C#, for instance, similar type of writing was reduced from "Fruit fruit = new Fruit();" to just "Fruit fruit = new();" (or "var fruit = new Fruit();" for that matter).
@kellymoses8566
@kellymoses8566 9 ай бұрын
type annotations are absolutely necessary for large applications.
@TommyCP
@TommyCP 9 ай бұрын
I always find that static typing is straightforward until you start using Numpy, Scikit, and others. Then everything becomes complicated as it is often not clear what bitsize your return values have. Would love to see an explanation on that.
@sto3359
@sto3359 9 ай бұрын
It would be great if it was possible to enable strict typing, say in setup.cfg for example.
@mecrayavcin
@mecrayavcin 6 ай бұрын
MYPY does not work in Windows Vscode! I installed both extension and library. I also checked flake8 plugin does not work as well
@xXKeightbestXx
@xXKeightbestXx 9 ай бұрын
Can you make a Video of your current set up of Pycharm? (Plugins/Fonts/Themes/Shortcuts)
@yoavmor9002
@yoavmor9002 9 ай бұрын
Typing makes bigger projects a breeze. Even if you reformat something big, just let it run, let it crash, find the first function call that violated the typing, fix it, rinse and repeat until everything works
@tharunkanna1401
@tharunkanna1401 9 ай бұрын
I have been using type annotations for a while now. It's really helpful. Great explanation. It's easy to debug and read as well. I have a request, can you make videos on JSON and Object serialisation in python objects
@aulerleandro
@aulerleandro 9 ай бұрын
I like annotations. But in my humble opinion, type annotation in Python lacks the automatic type inference of some statically typed languages (e.g. c++: `auto v = 10;` or Java: `var v = 10;` or rust: `let v = 10;` ). Without annotation, Python is a fully dynamic and automatic typed language, with annotation it mimics a static manual typed language (i.e. you must explicitly define the type). As it is good practice to always initialize variables, I think automatic inference would be a good feature and easy to be added.
@chaddaifouche536
@chaddaifouche536 9 ай бұрын
It doesn't really make sense to speak of inference for Python itself, since the interpreter doesn't care at all about the type hints, even if you put annotations in your program, it only get relegated into metadata and used by some libraries. Since Python doesn't even flinch if you put another type in your explicitly annotated variable, why should it try to infer something it won't use ? On the other hand most IDE and mypy do some type of inference so you don't have to annotate every variable you initialize to get autocompletion support, unless the type can't be inferred from the value (an empty list or dictionary can benefit from an annotation for exemple).
@aulerleandro
@aulerleandro 9 ай бұрын
The advantages (or not) of annotations in Python are already discussed in many places and there is no point in discussing them here again. My argument was only related to these interesting examples mentioned in the video: text: str = "text" obj: Obj = Obj() There is no benefit (in my humble opinion) to being explicit with the type if the variables are already initialized in the declaration because the type is implicit. But even so, I still think some form of annotation could be useful in giant codebases, for example. (just a speculative idea): text:= "text" obj:= Obj() The ":=" would mean that I want to use annotation but don't need to write boilerplate code.
@chaddaifouche536
@chaddaifouche536 9 ай бұрын
@@aulerleandroYou would need another syntax since ":=" is already the morse operator : "(var := expr)" is an expression that evaluates to expr while affecting expr to var. My main point wasn't the usefulness of annotations, I personally think they're amazing especially for function signatures. The point is there's two places where "type inference" would be useful for Python and they're already covered : - in IDE and mypy, text = "text" will already allow your IDE or mypy to know that the text variable contain a str, you can easily test that for yourself : "text." will only propose str methods. So there's already inference there. - in Python itself, type annotation are available via the __annotations__ dictionary and it's true that text = "text" won't populate that but given you can easily access type(text) everywhere you have the variable, this is not often useful or necessary in practice. This might be interesting if it was somehow able to give more precise types (list[int] instead of just the list you'll get through type()) though given Python dynamic typing and general disregard for type homogeneity that may be problematic. For exemple how is Python to know that when you write L = [1,2] you indeed wanted to build a list[int] and not a list[Any] where you'll append some string and floats later on ? It seems that inference would then be either useless or impossible in this regard.
@SusanAmberBruce
@SusanAmberBruce 9 ай бұрын
Please can you do a video about handling different file types in python, notably JSON and CSV also talk about how python handles the end of file delimiter, great content by the way, please keep it coming.
@Juli-540
@Juli-540 9 ай бұрын
8:58 -> Someone said: "A foolish consistency is the hobgoblin of little minds" 😁 I like your content, it's just a joke!
@KennethHaldbk
@KennethHaldbk 9 ай бұрын
I ❤ it. What about tip and tricks for pycharm?
@benbabu9404
@benbabu9404 9 ай бұрын
Maybe python will be a statically typed language in future???
@feldinho
@feldinho 9 ай бұрын
but `fruits: Fruits = Fruits()` has a practical benefit: it prevents that somewhere else in your code the `fruits` variable could be assigned to anything else than a `Fruits` object, like `fruits = 3`.
@Lets_code_together_
@Lets_code_together_ 9 ай бұрын
Thanks for great knowledge.....
@__christopher__
@__christopher__ 9 ай бұрын
I type my code because the computer can't read my handwriting. :-)
@ericwadebrown
@ericwadebrown 9 ай бұрын
So would you also add a return type on __init__()? If so, would it be None or Self?
@Indently
@Indently 9 ай бұрын
I always add that it returns None. Again, it's not necessary, but it's consistent.
@gauravsoni4025
@gauravsoni4025 9 ай бұрын
Can we use pipeline operator there instead of Mypy to specify other valid types ? BTW great video Federrricoo..... Love from India 🤝
@eldiasjr
@eldiasjr Ай бұрын
Awesome!
@chriskeo392
@chriskeo392 9 ай бұрын
You're my Jedi Master I'll follow your lead to the ends of 🌍 How about pydantic?
@Indently
@Indently 9 ай бұрын
I haven't tried Pydantic, but if there's anyone that knows the differences and have opinionated preferences on which one they prefer, I'd love to hear about it!
@DFsdf3443d
@DFsdf3443d 3 ай бұрын
i dont get why this isn't built into python itself and enforced by the interpreter itself instead of some external tool
@thepurplesmurf
@thepurplesmurf 9 ай бұрын
Honestly, I think for advanced programmer type annotations are a good helper, but they are heck of confusing for beginner. It makes it harder to read and to comprehend because you also have to know all the types and nuances to effectively use these annotations - exactly what beginner are not familiar with yet.
@MagnusAnand
@MagnusAnand 9 ай бұрын
Nice video
@Me__Myself__and__I
@Me__Myself__and__I 9 ай бұрын
There is actually a good reason to supply the type for something like "fruit: Fruit = Fruit()". By having the type annotation it makes this clear that an object instance is being created. Without the type annotation its unknown if this is a function call or a constructor. So really its not just useful for consistency (and consistency is a very good thing) but its does also have actual value in this case.
@Indently
@Indently 9 ай бұрын
A few of you have been pointing that out and I'm very grateful for hearing it :)
@TaleshicMatera
@TaleshicMatera 9 ай бұрын
Maybe one day PyCharm will fix the type annotation error with enumerate() where enumerate(T)->[T, Any] instead of ->[int, T]
@Carberra
@Carberra 8 ай бұрын
No type type = type? Sad.
@Indently
@Indently 8 ай бұрын
type type = type(type(type), (type), (type))
@Musician_Robert
@Musician_Robert 9 ай бұрын
The data variable is quite ironic.
@wazreacts
@wazreacts 9 ай бұрын
The python traffic lights don't have police that will book you for going through on a red....
@Indently
@Indently 9 ай бұрын
Nope, but you crashing your car because you ran a red light is directly relatable to the program. And call me old fashioned, but please don't tell me that Police are the only reason you don't run red lights. xD
@tehyonglip9203
@tehyonglip9203 2 ай бұрын
type annotations is really useful but useless at the same time, it makes us do almost the same job as a statically typed language, but without the speed and efficiency of them. If you are so disciplined to follow the rule of programming languages, you might as well use a lower programming language like c++
@Joseph_mohammed
@Joseph_mohammed 9 ай бұрын
Please make a video about arrow function in python
@yhavin
@yhavin 9 ай бұрын
There are none. Maybe you're thinking of JavaScript?
@tommy2cents492
@tommy2cents492 9 ай бұрын
Functions must have doc-strings. The type annotations are not an excuse for not having proper doc-strings.
@quixote798
@quixote798 8 ай бұрын
It's getting uglier and uglier. If you have time for this, study design patterns.
@taimunozhan
@taimunozhan 9 ай бұрын
Type annotations are useful but they are NOT self-documentation!
@StinkyCatFarts
@StinkyCatFarts 9 ай бұрын
If typing was causing you issues in Python, you’re not a good software engineer. Period T.
@valcubeto
@valcubeto 9 ай бұрын
def create_fruit() -> Fruit: fruit: Fruit = Fruit() return fruit
5 Random Useful Python Functions
12:32
Indently
Рет қаралды 21 М.
5 Useful Dunder Methods In Python
16:10
Indently
Рет қаралды 65 М.
«Жат бауыр» телехикаясы І 30 - бөлім | Соңғы бөлім
52:59
Qazaqstan TV / Қазақстан Ұлттық Арнасы
Рет қаралды 340 М.
"Идеальное" преступление
0:39
Кик Брейнс
Рет қаралды 1,4 МЛН
ССЫЛКА НА ИГРУ В КОММЕНТАХ #shorts
0:36
Паша Осадчий
Рет қаралды 8 МЛН
Маусымашар-2023 / Гала-концерт / АТУ қоштасу
1:27:35
Jaidarman OFFICIAL / JCI
Рет қаралды 390 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 666 М.
Python Typing - Type Hints & Annotations
24:46
Tech With Tim
Рет қаралды 117 М.
The most important Python script I ever wrote
19:58
John Watson Rooney
Рет қаралды 211 М.
5 Tips To Write Better Python Functions
15:59
Indently
Рет қаралды 114 М.
Avoiding import loops in Python
10:21
mCoding
Рет қаралды 95 М.
10 Nooby Mistakes Devs Often Make In Python
24:31
Indently
Рет қаралды 69 М.
5 Awful Python Mistakes To Avoid
22:13
Indently
Рет қаралды 28 М.
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 126 М.
20 Everyday Tips & Tricks in Python
25:18
Indently
Рет қаралды 28 М.
«Жат бауыр» телехикаясы І 30 - бөлім | Соңғы бөлім
52:59
Qazaqstan TV / Қазақстан Ұлттық Арнасы
Рет қаралды 340 М.