Skip to content
chantisnake edited this page Jul 18, 2017 · 14 revisions

this tutorial is aimed to introduce some of the more advanced feature of python.

Type Hinting

Type System is one of the best invention ever, since the beginning beginning of programming languages.

Unfortunately Python has one of the weakest type system in all the popular languages (the only one worse than python is JavaScript, and JavaScript sucks)

Recently Python developers finally realized that the weakness of python type system is hindering the development of large scale project (Like Lexos). Therefore we get something called Type Hinting.

Here is how you would normally write your functions:

def add(a, b):
    return a + b

Now with type hinting we will write function like this:

def add(a: int, b: int) -> int:
    return a + b

So why do we need type hinting?

  • Type hinting helps greatly with refactors
  • Type hinting can helps us prevent bug that is otherwise hard to discover.

Keyword Parameter

Normally, we pass parameter to functions like this:

def add(a, b):
    return a + b

add(1, 2)

This kind of passing is called use positional parameter. In this case positional parameter makes sense.

But, consider the following function:

def person(
      age:int, hight_cm:int, is_male:bool, is_working:bool,is_handsome:bool, blood_type:str, name: str)

when you see code like this:

person(21, 170, true, false, true, "o", "Cheng")

you gotta freak out, right?

This is a classic example of where positional parameter is useful:

person(
      age=21, hight_cm=170, is_male=true, is_working=false,
      is_handsome=true, blood_type="o", name="Cheng")

Much better, right? Unfortunately most cases in our program, is the second case (keyword parameter is necessary).

Therefore, keyword parameter should be the first choice.

Private Function

This is simple, just like C++ Needs private functions, python needs them too.

In python private function simply start your function and end your function with two underscore:

def __example__()

Notice: This is not really a private function, but a sign to tell people do not use this unless it is really necessary

Prefer Named Tuple to Tuple; Prefer Object to Dict

Unit Test

Numpy

Clone this wiki locally