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 :)
@thepurplesmurf8 ай бұрын
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. 😜
@Indently8 ай бұрын
I wish I could tell the construction workers outside my place the same thing :')
@logaspam8 ай бұрын
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.
@wootdafuq29258 ай бұрын
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 ;)
@christophhenninger64408 ай бұрын
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.
@unlomtrash8 ай бұрын
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 :)
@Indently8 ай бұрын
oooooooo, good point!
@Shivvorz8 ай бұрын
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
@ultimateownsz8 ай бұрын
First I thought you had another collab, then I realized mypy wasn't a person 😅😂
@Nerdimo8 ай бұрын
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.
@qwarlockz80172 ай бұрын
This is so clear and well structured! Thank you. This is how all languages should be taught!
@CASnumber8 ай бұрын
I just solved a problem for my company using type annotations. Literally the tool I used to solve the issue
@johnmckown12678 ай бұрын
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__I8 ай бұрын
Agree 100%. Strongly typed code is less buggy, easier to read and easier to maintain.
@markchadwick778 ай бұрын
Thanks. I recently pondered this question myself (typing obvious assignments). It's good to see you came to this conclusion.
@Me__Myself__and__I8 ай бұрын
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.
@j4s0n395 ай бұрын
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.
@rethanon8 ай бұрын
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_Youtube5 ай бұрын
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.
@eboyd538 ай бұрын
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.
@marcelpumpernickel8 ай бұрын
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__I8 ай бұрын
Also it makes it clear that Fruit() is a constructor and not just a function call.
@ghrasko3 ай бұрын
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
@loverboykimi8 ай бұрын
Man. you're writing very clean and smooth code. I get used to care these annotations by you. Many thanks.
@ego-lay_atman-bay8 ай бұрын
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.
@angelhdzdev8 ай бұрын
from typings import Any
@Diegos798 ай бұрын
Excellent as ever in all your precious videos! Thanks for your work. Please keep continue!
@huckleberryfinn87957 ай бұрын
I LOVE type annotations in Python.
@darcash17388 ай бұрын
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.
@TomLeg6 ай бұрын
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.
@falklumo8 ай бұрын
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 …
@Whatthetrash8 ай бұрын
I just installed mypy. Thanks for the video! I'll see if it helps. :)
@RedShipsofSpainAgain8 ай бұрын
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.
@MrStyles7848 ай бұрын
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
@alidev4257 ай бұрын
like your coding style👍👍
@voncolborn94378 ай бұрын
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__I8 ай бұрын
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.
@finnthirud8 ай бұрын
You're a great tutor! No cowboy coding culture here 🤠🐮
@kellymoses85668 ай бұрын
type annotations are absolutely necessary for large applications.
@tharunkanna14018 ай бұрын
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
@SusanAmberBruce8 ай бұрын
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.
@KennethHaldbk8 ай бұрын
I ❤ it. What about tip and tricks for pycharm?
@TommyCP8 ай бұрын
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.
@yoavmor90028 ай бұрын
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
@gauravsoni40257 ай бұрын
Can we use pipeline operator there instead of Mypy to specify other valid types ? BTW great video Federrricoo..... Love from India 🤝
@gownerjones8 ай бұрын
Python is my favorite language but dynamic typing is an abomination
@xXKeightbestXx8 ай бұрын
Can you make a Video of your current set up of Pycharm? (Plugins/Fonts/Themes/Shortcuts)
@feldinho8 ай бұрын
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`.
@sto33597 ай бұрын
It would be great if it was possible to enable strict typing, say in setup.cfg for example.
@anamoyeee8 ай бұрын
"Type annotations don't stop your code from running" What if i annotate my variable with exit()
@angelhdzdev8 ай бұрын
😂
@rusektor8 ай бұрын
"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_8 ай бұрын
Thanks for great knowledge.....
@cachamuertos8 ай бұрын
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-bay8 ай бұрын
You can set the type to "Class | None", then just check if the variable is none before accessing the object properties.
@Jason-b9t8 ай бұрын
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.
@benbabu94048 ай бұрын
Maybe python will be a statically typed language in future???
@huckleberryfinn87957 ай бұрын
Is there an extenstion like mypy for vscode?
@eldiasjr23 күн бұрын
Awesome!
@chriskeo3928 ай бұрын
You're my Jedi Master I'll follow your lead to the ends of 🌍 How about pydantic?
@Indently8 ай бұрын
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!
@aulerleandro8 ай бұрын
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.
@chaddaifouche5368 ай бұрын
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).
@aulerleandro8 ай бұрын
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.
@chaddaifouche5368 ай бұрын
@@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__8 ай бұрын
I type my code because the computer can't read my handwriting. :-)
@ismaelmerlo37307 ай бұрын
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-5408 ай бұрын
8:58 -> Someone said: "A foolish consistency is the hobgoblin of little minds" 😁 I like your content, it's just a joke!
@mecrayavcin5 ай бұрын
MYPY does not work in Windows Vscode! I installed both extension and library. I also checked flake8 plugin does not work as well
@ericwadebrown8 ай бұрын
So would you also add a return type on __init__()? If so, would it be None or Self?
@Indently8 ай бұрын
I always add that it returns None. Again, it's not necessary, but it's consistent.
@MagnusAnand8 ай бұрын
Nice video
@TaleshicMatera8 ай бұрын
Maybe one day PyCharm will fix the type annotation error with enumerate() where enumerate(T)->[T, Any] instead of ->[int, T]
@thepurplesmurf8 ай бұрын
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.
@DFsdf3443d2 ай бұрын
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__I8 ай бұрын
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.
@Indently8 ай бұрын
A few of you have been pointing that out and I'm very grateful for hearing it :)
@Musician_Robert8 ай бұрын
The data variable is quite ironic.
@Carberra7 ай бұрын
No type type = type? Sad.
@Indently7 ай бұрын
type type = type(type(type), (type), (type))
@wazreacts8 ай бұрын
The python traffic lights don't have police that will book you for going through on a red....
@Indently8 ай бұрын
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Ай бұрын
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++
@tommy2cents4928 ай бұрын
Functions must have doc-strings. The type annotations are not an excuse for not having proper doc-strings.
@Joseph_mohammed8 ай бұрын
Please make a video about arrow function in python
@yhavin8 ай бұрын
There are none. Maybe you're thinking of JavaScript?
@quixote7987 ай бұрын
It's getting uglier and uglier. If you have time for this, study design patterns.
@taimunozhan8 ай бұрын
Type annotations are useful but they are NOT self-documentation!
@StinkyCatFarts8 ай бұрын
If typing was causing you issues in Python, you’re not a good software engineer. Period T.
@valcubeto8 ай бұрын
def create_fruit() -> Fruit: fruit: Fruit = Fruit() return fruit