Python Typing - Type Hints & Annotations

Поделиться
HTML-код
  • Опубликовано: 25 янв 2025

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

  • @Chameleonll
    @Chameleonll 6 месяцев назад +4

    17:57 For anyone wondering, we could use Tuple[int, ...]. This way, we annotate that the tuple should only contain integers, but it can be of any length, so we don't have to type exactly 3 ints.

  • @gaurishgangwar
    @gaurishgangwar Год назад +19

    I think Optional (at 14:10) means different than being an optional argument. Optional[bool] means that the argument can either be bool or None.

    • @piraloco5864
      @piraloco5864 Год назад

      Kind of, your explanation on the optional type is 100% true, but you can still use it to represent optional arguments, since it means that if you dont pass the argument the type checker will accept it.

    • @rabinadk1
      @rabinadk1 Год назад +2

      I was about to comment the same. Optional type is kind of confusing to most of the people. It just means additionally None.

  • @martonturbuk3060
    @martonturbuk3060 3 года назад +23

    Hi there, I came here to comment on this recent video, so I get a bigger chance of you reading this.
    I just wanted to thank you for all the work that you did put in these videos. I watched several of your longer videos (The Complete Python Course For Beginners for example) and they are really good. You helped a lot of people to learn, and gain knowledge, for free. Keep up the good work, and thank you.

    • @bencipherx
      @bencipherx 3 года назад

      @@techwithtim8893 is that ur WhatsApp number?

    • @UrBigSisKey
      @UrBigSisKey 2 года назад

      That's thoughtful of you ... :)

  • @sanjaykrish8719
    @sanjaykrish8719 2 года назад

    Thanks!

  • @max.caimits
    @max.caimits 3 года назад +46

    From typing module docs:
    ❝Optional[X] is equivalent to X | None (or Union[X, None]).
    Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional.❞

    • @GeorgeSanger
      @GeorgeSanger Год назад

      Add to add to this setting a argument to optional[bool] now mean that you can set output to None e.g. foo(None), now inside the function output will be None not False. And this wouldn't be caught by mypy. I do believe that part is incorrect, but very useful video otherwise

    • @garfield-pro
      @garfield-pro Год назад +1

      Thanks for explaining Union type which Tim missed out.

  • @danielcrone9553
    @danielcrone9553 2 года назад +10

    Thanks for the great explanation! It'd be also good to add how people generally indicate more library-specific types like df in pandas, class, numpy, path variables.

    • @PeceniJaguar
      @PeceniJaguar 2 года назад +2

      You just use the Class that creates that object, e.g. `data: pd.DataFrame = pd.DataFrame(some_params_etc)`

  • @axis2010
    @axis2010 2 года назад +10

    As a few others have already commented, Tim’s explanation of Optional is incorrect. Optional means that the type can be None or the given type. e.g. Optional[bool] = False means that a user can pass in a value of type bool or None. I doubt Tim wants to allow the user to pass in None. The correct type should be bool = False

  • @paulzupan3732
    @paulzupan3732 2 года назад +6

    According to the mypy documentation, an Iterable is anything that can be used in a for loop. A Sequence is anything that supports both len and __getitem__.

  • @cn-ml
    @cn-ml Год назад +3

    Very informative, there are lots of things to add to this video, but you covered a great base. I would however like to see corrections on the Optional type, which you seem to have misunderstood a lot. It is definitely *NOT* used for optional parameters, but for parameters that can also be None (of course you could have optional default params: "name: Optional[int]=None"). Also in the Callable type optional does not provide default parameters, but Nullable params, but you still have to provide them in the call! If you want default params in callables, you should probably use the Protocol type.

  • @soupnoodles
    @soupnoodles 3 года назад +2

    Hey, thank you so much!
    Pretty helpful video, keep making these man :)

  • @18something
    @18something 3 года назад +6

    Optional is used more on the request payload validation, some of the fields are not always required. Not just to decorate an optional parameter

    • @18something
      @18something 3 года назад +1

      Types shine on facilitating validation more than documentation. Feel like you need to couple this topic with pydantic as well

    • @cn-ml
      @cn-ml Год назад

      You should probably use the NotRequired type then, instead of Optional.

  • @rossli8621
    @rossli8621 2 года назад

    Dude I just fell in love with your tutorial videos.

  • @Saitama-ur3lq
    @Saitama-ur3lq 2 года назад +2

    ah! the definitive edition of typescript for python is here lol

  • @larrystone654
    @larrystone654 2 года назад +2

    Your videos are so refreshingly clear! Question: If the typing library is used for the purpose of complaining about incorrect typing, why do you need to run the program through mypy instead of just running the python program and letting *it* complain?

  • @YoubiTheGreat
    @YoubiTheGreat Год назад

    In my case, VS Code/Python 3.11.5, just starting the video (5:05), int x = 1 already causes an error "Expression value is unused" Pylance. If I enter x: int = "Hi", "Hi" is underlined as an error : Expression of type "Literal['Hi']" cannot be assigned to declared type "int", so : int causes an error. Like x: str = 1, I get a Expression of type "Literal[1]" cannot be assigned to declared type "str" "Literal[1]" is incompatible with "str"Pylance.

  • @shikharpathak8510
    @shikharpathak8510 3 года назад +3

    How amazing it is... Like there is always a lot to learn. Thanks for taking us along ❤️

  • @sethutrun
    @sethutrun 3 года назад +1

    Love the python videos!! Thank you so much

  • @pianopianist5709
    @pianopianist5709 3 года назад +6

    I was watching your shorts video when I got this notification!

  • @loveafinni
    @loveafinni 5 месяцев назад

    Very helpful video. Thanks Tim.

  • @kingcrashplays
    @kingcrashplays 3 года назад +7

    This was the first thing I figured out due to the fact I come from a language like Java. Dynamically typed languages drive me insane, so whenever possible I always try to hint my variables with a specific type.

  • @kens_adventures
    @kens_adventures 3 года назад

    Thanks for this crush course while I am in the middle of my take home coding challenge for my job application

  • @meisherenow
    @meisherenow 5 месяцев назад

    Nicely explained in a short video.

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

    Great job bud. Thank you :)

  • @kaanb9192
    @kaanb9192 2 года назад

    this video was very helpful, since I saw some people use these type hints and annotations, I was wondering whether I am coding wrong. Turns out it is just for documentation...

  • @Absolotle
    @Absolotle 3 года назад +1

    Thank you! I didn't know that you could specify and test types like that.
    I noticed that when you tested the set as a sequence, (at 16:45) your set caontained ints instead of strings (you specified a sequence of str).
    Maybe that's the reason for the error and not the fact that you can't index a set?

    • @Absolotle
      @Absolotle 3 года назад +2

      ok, I tried and and, yes - also a set of strings will produce an error

  • @InglesConConfianza
    @InglesConConfianza Год назад

    GREAT VIDEO!

  • @mohamedfarag9136
    @mohamedfarag9136 Год назад

    Thank you very much for your explanation!

  • @pic01
    @pic01 3 года назад

    Thank you so much for this information, so helpful for me and everyone else

  • @derekreed6798
    @derekreed6798 Год назад

    Wow, how complicated type hints are pre 3.9. Great video as I needed to know this stuff (so thanks for your time), but I'll upgrade my python before using typehints.

  • @MsOfficeLearning
    @MsOfficeLearning 3 года назад

    Thank for the best tutorial sir.

  • @gameacer111
    @gameacer111 3 года назад +2

    Great info Tim! Thanks! Love the videos

  • @constantinci
    @constantinci 2 года назад +1

    What about declaring types of custom classes as methods/constructors parameters?

  • @tomgreg2008
    @tomgreg2008 Год назад

    Great video, thanks!

  • @RanjithKumar-jo7xf
    @RanjithKumar-jo7xf 2 года назад

    This is really awesome ❤️❣️

  • @CaptainBravo87
    @CaptainBravo87 2 года назад

    Great video!

  • @pratyushbehere3580
    @pratyushbehere3580 2 года назад

    Thanks, short and useful.

  • @alloutofafricanpolarbears
    @alloutofafricanpolarbears 3 года назад

    Thanks for the info dump. I have just recently started using this.

  • @nsomething2100
    @nsomething2100 2 года назад

    Hi there, question about the type "tuple" that you mention at 17:05 - What if there is a tuple with a large length (thousands of elements) - do we still need to specify the expected type at each position of the Tuple ?

    • @pD5V0DdsaoVhq
      @pD5V0DdsaoVhq Год назад

      Yes you do. But tuples are generally used in places like returning multiple values from a function. If you need 1000 elements, you should have used a list

  • @gerreyal
    @gerreyal 2 года назад

    Thanks Tim for the very usefull video.

  • @DrDeuteron
    @DrDeuteron 2 года назад

    On tuple type (circa 17:40), what if my tuple is 10,000 ints? Do I need to code:
    x: Tuple[int, int, ....10000 times...int]?
    Seems Akward

    • @ONLYUSEmyTOILET
      @ONLYUSEmyTOILET 2 года назад

      You could be specific and type it as x: tuple[(int,) * 10000] or just type it with arbitrary length as tuple[int, ...]

  • @MikeEldridge-e7l
    @MikeEldridge-e7l 5 месяцев назад

    Is there a way to enforce type annotations? Like to make sure developers are type annotating their code?

  • @Zoronoa01
    @Zoronoa01 2 года назад

    Thank you Tim!

  • @reza-iq5df
    @reza-iq5df 6 месяцев назад

    Great video thanks

  • @will2see
    @will2see 3 года назад +1

    Hi Tim, what keyboard are you using? I like the sound it makes ;-)

  • @ChrisLeftBlank
    @ChrisLeftBlank 11 месяцев назад

    12:30 But i thought at the start they've said "If you are looking to replace long string with easy command THIS IS NOT THAT VIDEO ...", but now it kind of is. ?

  • @Mdroudian
    @Mdroudian 2 года назад

    The tabnine is badass. Sourcery is also a great extension.

  • @WolfsInk
    @WolfsInk Год назад

    And to think I'd just finished revamping my project creator code from the last video from you I'd watch... XD I wonder how well this would interact with pylint.

  • @prueba-numero-uno
    @prueba-numero-uno 3 года назад +1

    It's amazing, I need to find how to use Type Hints on Django. When I use values like Dates, Email, Passwords, etc...

  • @garfield-pro
    @garfield-pro Год назад

    Hey Tim, How do we hint the type of *args and **kwargs?

  • @jleonardolemos
    @jleonardolemos 2 года назад

    great video, thanks!!!!

  • @prashantlawhatre7007
    @prashantlawhatre7007 2 года назад

    14:23 So, Optional[bool] = Union[bool,None] and not because it has default value.

  • @miguelvasquez9849
    @miguelvasquez9849 2 года назад

    Should i use Sequence[str] instead of List[str]? For your example [‘a’,’b’]

  • @squidproxy136
    @squidproxy136 2 года назад

    amazing, thanks

  • @nunezkant
    @nunezkant 2 года назад

    What about numpy arrays ?

  • @sushantgupta4757
    @sushantgupta4757 Год назад

    Thank you so much

  • @taharatamin3434
    @taharatamin3434 3 года назад +6

    Tim, create a tutorial on docker if possible

  • @splendorman7922
    @splendorman7922 2 года назад

    x: list[list[int]] = [[2,3],[1,6]] works for me. is it because of version difference? Tried it on v3.9

  • @fivefournino
    @fivefournino 3 года назад

    How would one type hint for objects you pull in from other packages? (Dataframe in-np array out, list in-praw out, etc)

    • @BiologyIsHot
      @BiologyIsHot 3 года назад +1

      Import and then put the class name
      ie var1: pd.DataFrame

  • @HubertRozmarynowski
    @HubertRozmarynowski 3 года назад

    Thanks for the video, Tim. How would you type a list that can store both float and int types?

  • @freakpandor
    @freakpandor 10 месяцев назад

    What if an object is a parameter?

  • @miloventimiglia8547
    @miloventimiglia8547 Год назад

    Isn't the case that if you find yourself needing static feature, you should opt in for Java? Or a more advance language? Python leads to a lot of overheads whereas in Java everything is already built in

  • @محسن-ه1ه1ث
    @محسن-ه1ه1ث 3 года назад

    how should we insert persian in kivy

  • @snippletrap
    @snippletrap 2 года назад

    pyright reports type errors in your editor or IDE, so you don't need to run mypy

  • @andresyesidmorenovilla7888
    @andresyesidmorenovilla7888 3 года назад

    Hi tim, excellent video! thank you so much. I have a question, how would one go about typing a variable which is a dictionary, whose keys are all strings but whose values' types may be different (i.e int, float, bool, etc)?

    • @cn-ml
      @cn-ml Год назад +1

      A bit late, but for people who are seeing this today: Dict[str, int | float | bool | etc]. Just use a Union of all types as a value. I personally prefer TypedDict to assign types for specific keys.

  • @iluvsyphonfilter
    @iluvsyphonfilter 3 года назад

    Hey Tim yesterday I was working on a Flask project and I noticed in the terminal that it made a GET request to a route from another project and of course it got a 404 because that route don't exist in the new project.
    I got scared and don't know what it could be, do you think someone got into my localhost? The IP address from the GET request was from my localhost.

    • @iluvsyphonfilter
      @iluvsyphonfilter 3 года назад

      @@techwithtim8893 Nevermind, I think that was caused by something related to telemetry in the browser or something like that, anyways now I'm keeping the resource monitor and task manager opened on the side to see if I catch something strange in my network.

  • @gustavopoa
    @gustavopoa 3 года назад

    Thanks Tim

  • @umeshlab987
    @umeshlab987 3 года назад

    What software do you use for thumbnails

  • @raziyehnikookolah6107
    @raziyehnikookolah6107 Год назад

    very useful

  • @WillsonMock
    @WillsonMock 2 года назад

    Does anyone know how to use a custom class definition as a type?

    • @pD5V0DdsaoVhq
      @pD5V0DdsaoVhq Год назад +2

      The class name itself is a valid type.

  • @uKaigo
    @uKaigo 3 года назад +5

    Isn't the Optional type used only when None can be passed? AFAIK when you have an have an optional parameter you shouldn't type it with Optional unless it accepts None
    Also Optional[T] is the same as Union[T, None], implying this

    • @ignis2982
      @ignis2982 3 года назад

      Yes, but that only applies if you type hint return types.

    • @uKaigo
      @uKaigo 3 года назад

      @@ignis2982 oh, I thought it applied to parameters too, thanks

  • @joseflat
    @joseflat 3 года назад

    Anyone knows, how would I typehint , when I return an object of some of my classes?

    • @nyscire877
      @nyscire877 3 года назад

      Just typehint your class name. For example, if you namedyour class "Foo" you would do something like that:
      def func(parameter: Any) -> Foo

  • @itaydvash
    @itaydvash 3 года назад

    What about objects I created?

  • @John_Shi305
    @John_Shi305 2 года назад

    非常感谢, thank you

  • @tcgvsocg1458
    @tcgvsocg1458 3 года назад

    Can you do a video on "make a platformer game in python 2021" or beat them all
    Thx a lot

  • @anugrahtriramadhan9300
    @anugrahtriramadhan9300 3 года назад

    How about iterable?

  • @murphygreen8484
    @murphygreen8484 3 года назад

    Date types?

  • @mback12000
    @mback12000 10 месяцев назад

    So whats the usefulness of type hinting - compared to just comments - if you're not using an analysis tool?

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

      Making your code readable
      If you don't understand how, open up a big Python project without type annotations and try to understand the code. You'll quickly figure out how inconvenient it is to not know the types of variables and function parameters.

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

      @@StepwaveMusic Thanks. I also since discovered (learned) that may other libraries can use type hinting. For example, I've been working in FastAPI, and it draws a lot of info from type hints including automating documentation.

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

      @@mback12000 the typing library is a standard library, so indeed, it is interoperable with Python. This is the case with most libraries, although it depends.

  • @pkavenger9990
    @pkavenger9990 2 года назад

    16:51 I think it gave an error because you specified Sequence [str] but you put "int" in the function's parameter instead of a string.

  • @this-is-bioman
    @this-is-bioman 2 года назад

    This is an excellent presentation with nice large and readable font, dark background and timestamps!
    Python is by far the most stupid language LOL By design dynamically typed and without access modifiers, but yet people demand these features so they added type hints and use underscores for private members. How can you not love this illogical design decisions? 🤣🤣🤣

  • @OmidAtaollahi
    @OmidAtaollahi 3 месяца назад

    great. tnx

  • @bencipherx
    @bencipherx 3 года назад +1

    I lost a German job interview cos of type hinting, no more is that happening again 🦁

    • @bencipherx
      @bencipherx 3 года назад

      @Anne-[S]EX-Vlog Go to My Channel yes , it's type will be the class provided its imported or implemented in the same module

  • @lt_academy
    @lt_academy 2 года назад

    well done )

  • @rajveer.singh-code
    @rajveer.singh-code 6 месяцев назад

    Annotated?

  • @dominikwodarczyk6714
    @dominikwodarczyk6714 3 года назад

    Also Union is pretty useful

  • @johnsmith-fk7fw
    @johnsmith-fk7fw 3 года назад +2

    i make it a point to make my code as hard as possible to read, like a puzzle. i call it 'davinci code' 😎

  • @BRLN1
    @BRLN1 3 года назад +5

    You should have waited with this video until python 3.10 got published in a few weeks!
    However most stuff you present here is even with python 3.9 already deprecated!

  • @paschalokafor9043
    @paschalokafor9043 Год назад

    @16.47 minutes you should have tried a set of strings not numbers.

  • @ahmedyousif4782
    @ahmedyousif4782 3 года назад

    The only time that I used types in python is when dealing with data classes

  • @haohuynhnhat3881
    @haohuynhnhat3881 3 года назад

    you can do list[bla, bla] in python >= 3.9, and in 5 years the List from typing.List will be deprecated

  • @spinettico
    @spinettico 3 месяца назад

    cristal clear

  • @ahmedyousif4782
    @ahmedyousif4782 3 года назад +2

    ALGOEXPERT SHUT UP I DON'T WANT TO BE A SOFTWARE ENGINEER AT GOOGLE

  • @user-jf4wc7tf9v
    @user-jf4wc7tf9v 3 года назад +20

    NICE VIDEO!! Very engaging from the beginning to the END. Nevertheless Business and investment are the best way to make money irrespective of which party make it to the oval office.

    • @jimmys.fuller3659
      @jimmys.fuller3659 3 года назад

      Absolutely right, I got 70% of my total portfolio in crypto and I have been making good profits.

    • @rosalinda1965
      @rosalinda1965 3 года назад

      I wanted to invest more in crypto, but the fluctuations in crypto value discouraged me into dumping.

    • @Flow.Monkam
      @Flow.Monkam 3 года назад

      @@rosalinda1965 That won't bother you if you trade with a professional like Mr Nicholas howard.

    • @anitapearl2706
      @anitapearl2706 3 года назад

      Wow 😮I’m just shocked you mentioned and recommended Mr. Nicholas howard I thought people don’t know him, he is really awesome.

    • @Flow.Monkam
      @Flow.Monkam 3 года назад

      @@anitapearl2706 Yeah I know him, who doesn't know Mr Nicholas howard of (HSBC SECURITY (USA) INC).

  • @Adedeji-v9z
    @Adedeji-v9z Месяц назад

    @13:12 😂

  • @binaprajapati7709
    @binaprajapati7709 3 года назад +2

    Can we get some rust pleaseeee 🥺🥺

  • @iddo-ba
    @iddo-ba 3 года назад

    Hi

  • @apnagamer61
    @apnagamer61 3 года назад +1

    1st comments

  • @hanyanglee9018
    @hanyanglee9018 2 года назад

    Guys, rename this language as MyTython, or at least Tython.

  • @SenselessTalk
    @SenselessTalk 3 года назад

    First

  • @PhongNguyen-jd3fw
    @PhongNguyen-jd3fw 3 года назад

    So this is typescript in python 😂

  • @maqdala
    @maqdala 2 года назад

    What font is that? What an L!