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

Поделиться
HTML-код
  • Опубликовано: 9 июн 2024
  • In today’s video we will be learning about type annotations in Python, and also why I always try to type everything with no exceptions.
    ▶ Become job-ready with Python:
    www.indently.io
    ▶ Follow me on Instagram:
    / indentlyreels
    00:00 Learning Python made simple
    00:05 Intro
    00:32 Getting started
    03:35 Mypy
    05:12 More benefits
    08:26 Isn't it redundant?
    11:10 Your thoughts

Комментарии • 89

  • @Indently
    @Indently  2 месяца назад +15

    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 2 месяца назад +1

      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  2 месяца назад

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

  • @logaspam
    @logaspam 2 месяца назад +58

    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.

  • @ultimateownsz
    @ultimateownsz 2 месяца назад +24

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

  • @unlomtrash
    @unlomtrash 2 месяца назад +13

    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  2 месяца назад +4

      oooooooo, good point!

  • @christophhenninger6440
    @christophhenninger6440 2 месяца назад +3

    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.

  • @wootdafuq2925
    @wootdafuq2925 2 месяца назад +2

    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 ;)

  • @Shivvorz
    @Shivvorz 2 месяца назад +4

    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 2 месяца назад +2

    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.

  • @Diegos79
    @Diegos79 2 месяца назад

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

  • @loverboykimi
    @loverboykimi 2 месяца назад

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

  • @johnmckown1267
    @johnmckown1267 2 месяца назад +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 2 месяца назад

      Agree 100%. Strongly typed code is less buggy, easier to read and easier to maintain.

  • @Dunning_Kruger_Is__On_Youtube
    @Dunning_Kruger_Is__On_Youtube 3 дня назад

    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.

  • @CASnumber
    @CASnumber 2 месяца назад +1

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

  • @TomLeg
    @TomLeg Месяц назад

    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.

  • @ego-lay_atman-bay
    @ego-lay_atman-bay 2 месяца назад +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.

  • @markchadwick77
    @markchadwick77 2 месяца назад +4

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

  • @Lets_code_together_
    @Lets_code_together_ 2 месяца назад

    Thanks for great knowledge.....

  • @marcelpumpernickel
    @marcelpumpernickel 2 месяца назад +4

    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 2 месяца назад

      Also it makes it clear that Fruit() is a constructor and not just a function call.

  • @huckleberryfinn8795
    @huckleberryfinn8795 Месяц назад

    I LOVE type annotations in Python.

  • @Me__Myself__and__I
    @Me__Myself__and__I 2 месяца назад +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.

  • @tharunkanna1401
    @tharunkanna1401 2 месяца назад +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

  • @finnthirud
    @finnthirud 2 месяца назад

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

  • @alidev425
    @alidev425 2 месяца назад

    like your coding style👍👍

  • @Whatthetrash
    @Whatthetrash 2 месяца назад

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

  • @rethanon
    @rethanon 2 месяца назад +1

    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.

  • @eboyd53
    @eboyd53 2 месяца назад

    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.

  • @darcash1738
    @darcash1738 2 месяца назад +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.

  • @cachamuertos
    @cachamuertos 2 месяца назад +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 2 месяца назад +1

      You can set the type to "Class | None", then just check if the variable is none before accessing the object properties.

    • @user-vt9bp2ei1w
      @user-vt9bp2ei1w 2 месяца назад

      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.

  • @Juli-540
    @Juli-540 2 месяца назад +2

    8:58 -> Someone said: "A foolish consistency is the hobgoblin of little minds" 😁 I like your content, it's just a joke!

  • @KennethHaldbk
    @KennethHaldbk 2 месяца назад

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

  • @anamoyeee
    @anamoyeee 2 месяца назад +3

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

  • @SusanAmberBruce
    @SusanAmberBruce 2 месяца назад

    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.

  • @voncolborn9437
    @voncolborn9437 2 месяца назад +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 2 месяца назад

      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.

  • @RedShipsofSpainAgain
    @RedShipsofSpainAgain 2 месяца назад +1

    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 2 месяца назад

      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

  • @MagnusAnand
    @MagnusAnand 2 месяца назад

    Nice video

  • @gownerjones1450
    @gownerjones1450 2 месяца назад +4

    Python is my favorite language but dynamic typing is an abomination

  • @gauravsoni4025
    @gauravsoni4025 2 месяца назад

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

  • @xXKeightbestXx
    @xXKeightbestXx 2 месяца назад

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

  • @ismaelmerlo3730
    @ismaelmerlo3730 Месяц назад

    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.

  • @huckleberryfinn8795
    @huckleberryfinn8795 Месяц назад

    Is there an extenstion like mypy for vscode?

  • @kellymoses8566
    @kellymoses8566 2 месяца назад

    type annotations are absolutely necessary for large applications.

  • @benbabu9404
    @benbabu9404 2 месяца назад +1

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

  • @ericwadebrown
    @ericwadebrown 2 месяца назад

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

    • @Indently
      @Indently  2 месяца назад +2

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

  • @TommyCP
    @TommyCP 2 месяца назад

    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.

  • @falklumo
    @falklumo 2 месяца назад

    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 …

  • @rusektor
    @rusektor 2 месяца назад +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).

  • @sto3359
    @sto3359 2 месяца назад

    It would be great if it was possible to enable strict typing, say in setup.cfg for example.

  • @yoavmor9002
    @yoavmor9002 2 месяца назад

    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 2 месяца назад

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

  • @chriskeo392
    @chriskeo392 2 месяца назад +1

    You're my Jedi Master
    I'll follow your lead to the ends of 🌍
    How about pydantic?

    • @Indently
      @Indently  2 месяца назад

      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__ 2 месяца назад +2

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

  • @Robert_11911
    @Robert_11911 2 месяца назад

    The data variable is quite ironic.

  • @TaleshicMatera
    @TaleshicMatera 2 месяца назад

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

  • @aulerleandro
    @aulerleandro 2 месяца назад +1

    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 2 месяца назад +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 2 месяца назад

      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 2 месяца назад

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

  • @Me__Myself__and__I
    @Me__Myself__and__I 2 месяца назад

    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  2 месяца назад +1

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

  • @Carberra
    @Carberra Месяц назад

    No type type = type? Sad.

    • @Indently
      @Indently  Месяц назад

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

  • @thepurplesmurf
    @thepurplesmurf 2 месяца назад +3

    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.

  • @wazreacts
    @wazreacts 2 месяца назад

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

    • @Indently
      @Indently  2 месяца назад +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

  • @Joseph_mohammed
    @Joseph_mohammed 2 месяца назад

    Please make a video about arrow function in python

    • @yhavin
      @yhavin 2 месяца назад +1

      There are none. Maybe you're thinking of JavaScript?

  • @tommy2cents492
    @tommy2cents492 2 месяца назад

    Functions must have doc-strings. The type annotations are not an excuse for not having proper doc-strings.

  • @quixote798
    @quixote798 2 месяца назад

    It's getting uglier and uglier.
    If you have time for this, study design patterns.

  • @taimunozhan
    @taimunozhan 2 месяца назад

    Type annotations are useful but they are NOT self-documentation!

  • @StinkyCatFarts
    @StinkyCatFarts 2 месяца назад

    If typing was causing you issues in Python, you’re not a good software engineer. Period T.

  • @valcubeto
    @valcubeto 2 месяца назад +1

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