DEV Community

Cover image for You are coding the wrong way in Python if you aren't using these two libraries
Rohith Gilla
Rohith Gilla

Posted on • Originally published at rohithgilla.mdx.one

You are coding the wrong way in Python if you aren't using these two libraries

https://media.giphy.com/media/4OBq5v6J4pgJuZ2Cnj/giphy.gif
Hello amazing developers

Table of Contents

  • Motivation
  • Introduction
  • Typing
    • Variables
    • Lists
    • Dictionary
    • Functions
    • Classes
  • Conclusion
  • Resources

Motivation

What makes people love (sometimes hate 😛) TypeScript more than JavaScript?

It's the typing, the type safety. They know that there will be a safety net beneath them that catches many bugs and shouts at us if we do mistakes.

It's not just that it's the auto-suggestion that matters too, it would feel amazing right when you get the best auto completes and the methods for the variable.

Now what if I say we can you could kinda get it in python. It feels great right.

https://media.giphy.com/media/aWPGuTlDqq2yc/giphy.gif

Now since we know python is an interpreted language and it doesn't have complier for itself so we can't entirely replicate typescript but at least try to use types wherever possible.

TL;DR on how typescript works, it takes the entire entire script code complies it into a JavaScript file, the complier does all the type checking.

Python is a dynamically typed language

Introduction

From python 3.5 we have this amazing library which is build inside python, it's the typing library. We can't cover entire library but applying Pareto principle (80-20 rule) I will try to cover a few important parts of the library.

We use it along with a power type checking library mypy.

We will be sliding over the following topics in brief

  • Basic Variables
  • Lists
  • Dictionary
  • Functions
  • Classes

https://media.giphy.com/media/cAhGmJPBqsXAlDTYHi/giphy.gif

Let's start

IDE Setup

Please install the following extensions for VSCode

MyPy

Error Lens (Optional)

Typing

Variables

  • Integer
  • Float
  • String
int_typed:int = 4

float_typed:float = 1.2

string_typed:str = "hello"
Enter fullscreen mode Exit fullscreen mode

Let us see what happens if we try to assign them a different value.

Int Error

Lists

To know more about Lists you have to know about Sequence

Sequence

In Python, sequence is the generic term for an ordered set. There are several types of sequences in Python, the following three are the most important.

Lists

Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable - they can be changed. Elements can be reassigned or removed, and new elements can be inserted.

from typing import List
int_typed_list:List[int] = []
Enter fullscreen mode Exit fullscreen mode

List
Shouts for type errors

But but but but in TypeScript we have any keyword if we want dynamic array

Yes the golden Any even exists here too

from typing import Any, List

int_typed:int = 4

float_typed:float = 1.2

string_typed:str = "hello"

int_typed_list:List[int] = []

int_typed_list.append(int_typed)

any_typed_list: List[Any] = []
any_typed_list.append(int_typed)
any_typed_list.append(string_typed)
any_typed_list.append(float_typed)
any_typed_list.append(int_typed_list)
Enter fullscreen mode Exit fullscreen mode

Power of any
No shouting 🤫

Dictionary

For this section Picture speaks louder than words

from typing import Dict

x: Dict[str, int] = {'followers': 1110} 

x['abc'] = 123

x.keys()

x.values()
Enter fullscreen mode Exit fullscreen mode

Overall
It reads the keys if we define in code and help us in auto complete

Keys
Now we know that keys() returns a list of str

Values
Now we know that values() returns a list of int

Functions

My all time favourite definition of function is depicted in the picture below.

Function

def get_avg(num1:int, num2:int) -> float:
    return (num1+num2)/2

get_avg(12,9)
Enter fullscreen mode Exit fullscreen mode

Function shouts
Function shouts

Classes

We may need a solution when we require custom classes to hold and use our data. Then we could similar to this

import math as m

class Vector:
    def __init__(self, x:float,y:float) -> None:
        self.x = x
        self.y = y

    def calculate_magnitude(self) -> float:
        return m.sqrt(m.pow(self.x,2)+ m.pow(self.y,2))

v = Vector(1,1)
Enter fullscreen mode Exit fullscreen mode

Vector Class

You get the beautiful autocomplete again with details 💫

Conclusion

With great power comes great responsibility

As said in the picture, with great power comes great responsibility.
Python dynamic types gives us very easy to get started with learning python but at the same time increases the chances to create bugs unintentionally.

The typing gets even better in Python 3.9 and I hope it gets better and better as we progress.

Small changes can great a huge impact in the code, so please start using types, MyPy and feel safe.

I kept it brief but please do let me know if diving deeper helps, feedback is really appreciated.

Resources

MyPY

Typing

P.S My Twitter DMs are always open if you want to discuss collaboration opportunities or request on writing for a topic

https://media1.tenor.com/images/40317e3f3b28d57c89edceb1d75832c2/tenor.gif?itemid=16119732

Thanks
Rohith Gilla

Top comments (0)