Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Static Typing in Python 3.6

    Will ButtonWill Button

    In this lesson, you will learn how to statically type variables in Python 3.6 Static typing can help you avoid errors when consumers of your variables and functions call them with the incorrect data type. You will learn how to statically type strings, integers, booleans, Lists and Dicts. You will also learn how to automatically check for typing errors when coding and as part of your build workflow.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: If you've ever had one of those times in Python where you create a function and then someone else comes along and they try to use your function, even though you tested it they come back to you saying that your function isn't working.

    After a lot of conversations back and forth and troubleshooting, you find out that they did something like this where they were supposed to use an integer and instead supplied a string. Now in Python 3.6 you can do static typing and prevent some of those errors from occurring.

    To static we type a variable in Python. You declare your variable like you always would and then add a colon and the type of variable that it is. In this case we want A and B to be integers so we can specify it as A:int and B: int.

    Now because I'm using Pycharm it's going to do the automatic type checking and then highlight the variable Fu here and says that it's expecting a type integer but got a string instead. We know right away that that's not going to work.

    If you're not using Pycharm as your Python editor you're not out of luck because you can use Mypy to perform the same thing. You can find all the documentation from Mypy on their website at Mypy-lang-org and you can use pip to install it on your own system.

    Then you can use Mypy by supplying the Mypy command and the name of the file you want to check. When it fails it gives you the line number that it failed on as well as the error that caused it to fail. This is cool because you can integrate this with your CI or CD solution and help identify these errors at build time rather than waiting for them to be discovered in production.

    In addition to declaring integers you can declare string variables, Booleans. By importing from the typing module, dict enlist, you can declare a list with the data type that should be in the list. You can do the same for dict to specify what the structure of the dicts should look like.