Simple PyType Examples

Introduction

PyType (https://github.com/google/pytype) enables you to add typing to your Python code. This can be a huge help for larger projects especially. One of the biggest issues with building larger projects in Python, is when calling a function or method within a library – determining what type of object you are supposed to send to that method. This is all solved when the type declarations are made in the function signature.

Installing PyType

You can install PyType using pip with the following command:

pip install pytype

Or for Python3:

pip3 install pytype

Analyzing a File

You can test a python file or directory using pytype like so:

pytype my_file.py

Or on a directory like so:

pytype my_directory/

Adding Types in Code

You should write your code with typing now. Here’s what that looks like in a function signature:

def multiply(value_one: int, value_two: int) -> int:
  return value_one * value_two

You just add a “:” after the parameter declaration, then follow with the expected type. At the end of the function signature, add a “->” followed by the function’s return type.

Here are a few more examples:

def upper_print(to_print: str) -> None:
  print(to_print.upper())
from typing import List

def remove_from_array(to_remove: int, from_array: List[int]) -> List[int]:
  temp = list()
  for i in from_array:
    if i != to_remove:
      temp.append(i)
  return temp
from typing import Dict, List

def return_keys(d: Dict[str, int]) -> List[str]:
  return list(d.keys())
class MyClass:
  def __init__(self):
    self.x = 10

def update_x(instance: MyClass) -> MyClass:
  instance.x = 20
  return instance

Happy Hacking!

About the author

I do a lot of stuff. I'm a decent hacker. I jump out of airplanes a lot. Done some firefighting and stuff. Philosophy all the time, make music, acting in awesome indie films. Just, a lot of stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.