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

  Рет қаралды 34,581

Indently

Indently

Күн бұрын

Пікірлер: 96
@Indently
@Indently 8 ай бұрын
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 8 ай бұрын
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 8 ай бұрын
I wish I could tell the construction workers outside my place the same thing :')
@logaspam
@logaspam 8 ай бұрын
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.
@wootdafuq2925
@wootdafuq2925 8 ай бұрын
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 ;)
@christophhenninger6440
@christophhenninger6440 8 ай бұрын
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.
@unlomtrash
@unlomtrash 8 ай бұрын
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 8 ай бұрын
oooooooo, good point!
@Shivvorz
@Shivvorz 8 ай бұрын
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
@ultimateownsz
@ultimateownsz 8 ай бұрын
First I thought you had another collab, then I realized mypy wasn't a person 😅😂
@Nerdimo
@Nerdimo 8 ай бұрын
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.
@qwarlockz8017
@qwarlockz8017 2 ай бұрын
This is so clear and well structured! Thank you. This is how all languages should be taught!
@CASnumber
@CASnumber 8 ай бұрын
I just solved a problem for my company using type annotations. Literally the tool I used to solve the issue
@johnmckown1267
@johnmckown1267 8 ай бұрын
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 8 ай бұрын
Agree 100%. Strongly typed code is less buggy, easier to read and easier to maintain.
@markchadwick77
@markchadwick77 8 ай бұрын
Thanks. I recently pondered this question myself (typing obvious assignments). It's good to see you came to this conclusion.
@Me__Myself__and__I
@Me__Myself__and__I 8 ай бұрын
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 5 ай бұрын
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.
@rethanon
@rethanon 8 ай бұрын
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.
@Dunning_Kruger_Is__On_Youtube
@Dunning_Kruger_Is__On_Youtube 5 ай бұрын
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.
@eboyd53
@eboyd53 8 ай бұрын
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.
@marcelpumpernickel
@marcelpumpernickel 8 ай бұрын
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 8 ай бұрын
Also it makes it clear that Fruit() is a constructor and not just a function call.
@ghrasko
@ghrasko 3 ай бұрын
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
@loverboykimi
@loverboykimi 8 ай бұрын
Man. you're writing very clean and smooth code. I get used to care these annotations by you. Many thanks.
@ego-lay_atman-bay
@ego-lay_atman-bay 8 ай бұрын
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 8 ай бұрын
from typings import Any
@Diegos79
@Diegos79 8 ай бұрын
Excellent as ever in all your precious videos! Thanks for your work. Please keep continue!
@huckleberryfinn8795
@huckleberryfinn8795 7 ай бұрын
I LOVE type annotations in Python.
@darcash1738
@darcash1738 8 ай бұрын
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.
@TomLeg
@TomLeg 6 ай бұрын
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.
@falklumo
@falklumo 8 ай бұрын
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 …
@Whatthetrash
@Whatthetrash 8 ай бұрын
I just installed mypy. Thanks for the video! I'll see if it helps. :)
@RedShipsofSpainAgain
@RedShipsofSpainAgain 8 ай бұрын
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 8 ай бұрын
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
@alidev425
@alidev425 7 ай бұрын
like your coding style👍👍
@voncolborn9437
@voncolborn9437 8 ай бұрын
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 8 ай бұрын
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.
@finnthirud
@finnthirud 8 ай бұрын
You're a great tutor! No cowboy coding culture here 🤠🐮
@kellymoses8566
@kellymoses8566 8 ай бұрын
type annotations are absolutely necessary for large applications.
@tharunkanna1401
@tharunkanna1401 8 ай бұрын
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
@SusanAmberBruce
@SusanAmberBruce 8 ай бұрын
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.
@KennethHaldbk
@KennethHaldbk 8 ай бұрын
I ❤ it. What about tip and tricks for pycharm?
@TommyCP
@TommyCP 8 ай бұрын
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.
@yoavmor9002
@yoavmor9002 8 ай бұрын
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
@gauravsoni4025
@gauravsoni4025 7 ай бұрын
Can we use pipeline operator there instead of Mypy to specify other valid types ? BTW great video Federrricoo..... Love from India 🤝
@gownerjones
@gownerjones 8 ай бұрын
Python is my favorite language but dynamic typing is an abomination
@xXKeightbestXx
@xXKeightbestXx 8 ай бұрын
Can you make a Video of your current set up of Pycharm? (Plugins/Fonts/Themes/Shortcuts)
@feldinho
@feldinho 8 ай бұрын
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`.
@sto3359
@sto3359 7 ай бұрын
It would be great if it was possible to enable strict typing, say in setup.cfg for example.
@anamoyeee
@anamoyeee 8 ай бұрын
"Type annotations don't stop your code from running" What if i annotate my variable with exit()
@angelhdzdev
@angelhdzdev 8 ай бұрын
😂
@rusektor
@rusektor 8 ай бұрын
"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).
@Lets_code_together_
@Lets_code_together_ 8 ай бұрын
Thanks for great knowledge.....
@cachamuertos
@cachamuertos 8 ай бұрын
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 8 ай бұрын
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 8 ай бұрын
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.
@benbabu9404
@benbabu9404 8 ай бұрын
Maybe python will be a statically typed language in future???
@huckleberryfinn8795
@huckleberryfinn8795 7 ай бұрын
Is there an extenstion like mypy for vscode?
@eldiasjr
@eldiasjr 23 күн бұрын
Awesome!
@chriskeo392
@chriskeo392 8 ай бұрын
You're my Jedi Master I'll follow your lead to the ends of 🌍 How about pydantic?
@Indently
@Indently 8 ай бұрын
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!
@aulerleandro
@aulerleandro 8 ай бұрын
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 8 ай бұрын
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 8 ай бұрын
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 8 ай бұрын
@@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.
@__christopher__
@__christopher__ 8 ай бұрын
I type my code because the computer can't read my handwriting. :-)
@ismaelmerlo3730
@ismaelmerlo3730 7 ай бұрын
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.
@Juli-540
@Juli-540 8 ай бұрын
8:58 -> Someone said: "A foolish consistency is the hobgoblin of little minds" 😁 I like your content, it's just a joke!
@mecrayavcin
@mecrayavcin 5 ай бұрын
MYPY does not work in Windows Vscode! I installed both extension and library. I also checked flake8 plugin does not work as well
@ericwadebrown
@ericwadebrown 8 ай бұрын
So would you also add a return type on __init__()? If so, would it be None or Self?
@Indently
@Indently 8 ай бұрын
I always add that it returns None. Again, it's not necessary, but it's consistent.
@MagnusAnand
@MagnusAnand 8 ай бұрын
Nice video
@TaleshicMatera
@TaleshicMatera 8 ай бұрын
Maybe one day PyCharm will fix the type annotation error with enumerate() where enumerate(T)->[T, Any] instead of ->[int, T]
@thepurplesmurf
@thepurplesmurf 8 ай бұрын
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.
@DFsdf3443d
@DFsdf3443d 2 ай бұрын
i dont get why this isn't built into python itself and enforced by the interpreter itself instead of some external tool
@Me__Myself__and__I
@Me__Myself__and__I 8 ай бұрын
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 8 ай бұрын
A few of you have been pointing that out and I'm very grateful for hearing it :)
@Musician_Robert
@Musician_Robert 8 ай бұрын
The data variable is quite ironic.
@Carberra
@Carberra 7 ай бұрын
No type type = type? Sad.
@Indently
@Indently 7 ай бұрын
type type = type(type(type), (type), (type))
@wazreacts
@wazreacts 8 ай бұрын
The python traffic lights don't have police that will book you for going through on a red....
@Indently
@Indently 8 ай бұрын
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 Ай бұрын
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++
@tommy2cents492
@tommy2cents492 8 ай бұрын
Functions must have doc-strings. The type annotations are not an excuse for not having proper doc-strings.
@Joseph_mohammed
@Joseph_mohammed 8 ай бұрын
Please make a video about arrow function in python
@yhavin
@yhavin 8 ай бұрын
There are none. Maybe you're thinking of JavaScript?
@quixote798
@quixote798 7 ай бұрын
It's getting uglier and uglier. If you have time for this, study design patterns.
@taimunozhan
@taimunozhan 8 ай бұрын
Type annotations are useful but they are NOT self-documentation!
@StinkyCatFarts
@StinkyCatFarts 8 ай бұрын
If typing was causing you issues in Python, you’re not a good software engineer. Period T.
@valcubeto
@valcubeto 8 ай бұрын
def create_fruit() -> Fruit: fruit: Fruit = Fruit() return fruit
5 Random Useful Python Functions
12:32
Indently
Рет қаралды 21 М.
5 Wacky Python Features
15:37
Indently
Рет қаралды 12 М.
Why no RONALDO?! 🤔⚽️
00:28
Celine Dept
Рет қаралды 32 МЛН
СКОЛЬКО ПАЛЬЦЕВ ТУТ?
00:16
Masomka
Рет қаралды 3,2 МЛН
Ice Cream or Surprise Trip Around the World?
00:31
Hungry FAM
Рет қаралды 21 МЛН
The most important Python script I ever wrote
19:58
John Watson Rooney
Рет қаралды 208 М.
20 Everyday Tips & Tricks in Python
25:18
Indently
Рет қаралды 26 М.
Python Typing - Type Hints & Annotations
24:46
Tech With Tim
Рет қаралды 115 М.
10 Nooby Mistakes Devs Often Make In Python
24:31
Indently
Рет қаралды 67 М.
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 122 М.
5 Cool Python One-Liners
12:23
Indently
Рет қаралды 36 М.
typing the untype-able with mypy plugins (advanced) anthony explains #574
25:06
10 Neat Ways To Use Underscore In Python
18:17
Indently
Рет қаралды 23 М.
Debugging 101: Replace print() with icecream ic()
12:36
NeuralNine
Рет қаралды 370 М.
How To Write Better Functions In Python
14:17
Indently
Рет қаралды 48 М.
Why no RONALDO?! 🤔⚽️
00:28
Celine Dept
Рет қаралды 32 МЛН