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

แชร์
ฝัง
  • เผยแพร่เมื่อ 13 ม.ค. 2025

ความคิดเห็น • 97

  • @Indently
    @Indently  9 หลายเดือนก่อน +22

    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 หลายเดือนก่อน +2

      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 หลายเดือนก่อน +1

      I wish I could tell the construction workers outside my place the same thing :')

  • @logaspam
    @logaspam 9 หลายเดือนก่อน +81

    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 9 หลายเดือนก่อน +4

    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 หลายเดือนก่อน +33

    First I thought you had another collab, then I realized mypy wasn't a person 😅😂

  • @qwarlockz8017
    @qwarlockz8017 4 หลายเดือนก่อน

    This is so clear and well structured! Thank you. This is how all languages should be taught!

  • @unlomtrash
    @unlomtrash 9 หลายเดือนก่อน +25

    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 หลายเดือนก่อน +6

      oooooooo, good point!

  • @loverboykimi
    @loverboykimi 9 หลายเดือนก่อน +1

    Man. you're writing very clean and smooth code. I get used to care these annotations by you. Many thanks.

  • @christophhenninger6440
    @christophhenninger6440 9 หลายเดือนก่อน +4

    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.

  • @Diegos79
    @Diegos79 9 หลายเดือนก่อน +1

    Excellent as ever in all your precious videos! Thanks for your work. Please keep continue!

  • @Shivvorz
    @Shivvorz 9 หลายเดือนก่อน +5

    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

  • @Nerdimo
    @Nerdimo 9 หลายเดือนก่อน +5

    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.

  • @footflaps
    @footflaps 13 วันที่ผ่านมา

    Very concise explanation.

  • @markchadwick77
    @markchadwick77 9 หลายเดือนก่อน +4

    Thanks. I recently pondered this question myself (typing obvious assignments). It's good to see you came to this conclusion.

  • @RedShipsofSpainAgain
    @RedShipsofSpainAgain 9 หลายเดือนก่อน +2

    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

  • @finnthirud
    @finnthirud 9 หลายเดือนก่อน +1

    You're a great tutor! No cowboy coding culture here 🤠🐮

  • @CASnumber
    @CASnumber 9 หลายเดือนก่อน +2

    I just solved a problem for my company using type annotations. Literally the tool I used to solve the issue

  • @alidev425
    @alidev425 9 หลายเดือนก่อน +1

    like your coding style👍👍

  • @dustcore
    @dustcore 28 วันที่ผ่านมา

    Thank you for explaining this. I was getting mad confused.

  • @johnmckown1267
    @johnmckown1267 9 หลายเดือนก่อน +6

    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.

  • @ego-lay_atman-bay
    @ego-lay_atman-bay 9 หลายเดือนก่อน +2

    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

  • @Whatthetrash
    @Whatthetrash 9 หลายเดือนก่อน +1

    I just installed mypy. Thanks for the video! I'll see if it helps. :)

  • @rethanon
    @rethanon 9 หลายเดือนก่อน +2

    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.

  • @marcelpumpernickel
    @marcelpumpernickel 9 หลายเดือนก่อน +7

    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.

  • @tharunkanna1401
    @tharunkanna1401 9 หลายเดือนก่อน +2

    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

  • @Me__Myself__and__I
    @Me__Myself__and__I 9 หลายเดือนก่อน +1

    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.

  • @Lets_code_together_
    @Lets_code_together_ 9 หลายเดือนก่อน

    Thanks for great knowledge.....

  • @darcash1738
    @darcash1738 9 หลายเดือนก่อน +1

    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.

  • @huckleberryfinn8795
    @huckleberryfinn8795 9 หลายเดือนก่อน +1

    I LOVE type annotations in Python.

  • @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.

  • @KennethHaldbk
    @KennethHaldbk 9 หลายเดือนก่อน

    I ❤ it.
    What about tip and tricks for pycharm?

  • @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.

  • @eldiasjr
    @eldiasjr 2 หลายเดือนก่อน

    Awesome!

  • @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.

  • @cachamuertos
    @cachamuertos 9 หลายเดือนก่อน +2

    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 หลายเดือนก่อน +1

      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.

  • @TomLeg
    @TomLeg 8 หลายเดือนก่อน

    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.

  • @voncolborn9437
    @voncolborn9437 9 หลายเดือนก่อน +1

    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.

  • @huckleberryfinn8795
    @huckleberryfinn8795 9 หลายเดือนก่อน

    Is there an extenstion like mypy for vscode?

  • @falklumo
    @falklumo 9 หลายเดือนก่อน +1

    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 …

  • @gauravsoni4025
    @gauravsoni4025 9 หลายเดือนก่อน

    Can we use pipeline operator there instead of Mypy to specify other valid types ?
    BTW great video Federrricoo.....
    Love from India 🤝

  • @Dunning_Kruger_Is__On_Youtube
    @Dunning_Kruger_Is__On_Youtube 7 หลายเดือนก่อน

    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.

  • @gownerjones
    @gownerjones 9 หลายเดือนก่อน +4

    Python is my favorite language but dynamic typing is an abomination

  • @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

  • @ismaelmerlo3730
    @ismaelmerlo3730 9 หลายเดือนก่อน

    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.

  • @anamoyeee
    @anamoyeee 9 หลายเดือนก่อน +4

    "Type annotations don't stop your code from running"
    What if i annotate my variable with exit()

    • @angelhdzdev
      @angelhdzdev 9 หลายเดือนก่อน

      😂

  • @ericwadebrown
    @ericwadebrown 9 หลายเดือนก่อน

    So would you also add a return type on __init__()? If so, would it be None or Self?

    • @Indently
      @Indently  9 หลายเดือนก่อน +3

      I always add that it returns None. Again, it's not necessary, but it's consistent.

  • @xXKeightbestXx
    @xXKeightbestXx 9 หลายเดือนก่อน

    Can you make a Video of your current set up of Pycharm? (Plugins/Fonts/Themes/Shortcuts)

  • @ghrasko
    @ghrasko 5 หลายเดือนก่อน

    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

  • @MagnusAnand
    @MagnusAnand 9 หลายเดือนก่อน

    Nice video

  • @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.

  • @benbabu9404
    @benbabu9404 9 หลายเดือนก่อน +1

    Maybe python will be a statically typed language in future???

  • @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

  • @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`.

  • @aulerleandro
    @aulerleandro 9 หลายเดือนก่อน +2

    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 หลายเดือนก่อน +1

      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.

  • @rusektor
    @rusektor 9 หลายเดือนก่อน +5

    "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).

  • @DFsdf3443d
    @DFsdf3443d 4 หลายเดือนก่อน

    i dont get why this isn't built into python itself and enforced by the interpreter itself instead of some external tool

  • @chriskeo392
    @chriskeo392 9 หลายเดือนก่อน +1

    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!

  • @__christopher__
    @__christopher__ 9 หลายเดือนก่อน +2

    I type my code because the computer can't read my handwriting. :-)

  • @thepurplesmurf
    @thepurplesmurf 9 หลายเดือนก่อน +4

    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.

  • @Carberra
    @Carberra 9 หลายเดือนก่อน

    No type type = type? Sad.

    • @Indently
      @Indently  9 หลายเดือนก่อน

      type type = type(type(type), (type), (type))

  • @Musician_Robert
    @Musician_Robert 9 หลายเดือนก่อน

    The data variable is quite ironic.

  • @TaleshicMatera
    @TaleshicMatera 9 หลายเดือนก่อน

    Maybe one day PyCharm will fix the type annotation error with enumerate() where enumerate(T)->[T, Any] instead of ->[int, T]

  • @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 หลายเดือนก่อน +1

      A few of you have been pointing that out and I'm very grateful for hearing it :)

  • @wazreacts
    @wazreacts 9 หลายเดือนก่อน

    The python traffic lights don't have police that will book you for going through on a red....

    • @Indently
      @Indently  9 หลายเดือนก่อน +1

      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

  • @sebbyteh9203
    @sebbyteh9203 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 หลายเดือนก่อน +1

      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 9 หลายเดือนก่อน

    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 หลายเดือนก่อน +2

    def create_fruit() -> Fruit:
    fruit: Fruit = Fruit()
    return fruit