Lesson: Introduction to SmartPy

Ask Question

Chapter 8

Understanding how SmartPy infers data types


As readers familiar with Python would know that Python is a dynamically typed language.

This is in contrast to languages like C, Rust, OCaml (the language with which Tezos blockchain is built in) which are statically typed languages.

For example, let us contrast how one would define a variable that stores the number 5 in C and Python.

C Code:
int number = 5
Python Code:
number = 5

As you can see, in Python you don’t need to define the type of number beforehand. The compiler does the heavy lifting to infer types for you.

For more information on type checking in Python, we recommend skimming through this article.

Study Time:

Why bother learning about types?

Just like in Python, most of the time there is no need to specify the types in SmartPy. For a number of reasons (e.g. because SmartPy’s target language, Michelson, requires types), each SmartPy expression does however need a type.

While most of the time you will not write many types explicitly it is beneficial to at least have a basic understanding of what they are.

Understanding of types in SmartPy greatly helps in understanding & debugging error messages while writing smart contracts.

How does SmartPy deal with types?

SmartPy uses type inference in order to determine each expression’s type. In practice this means that information about an expression is gathered according to its usage.

Remember, our Bank contract example?

class Cryptobot(sp.Contract):
   def __init__(self):
       self.init(name = "World Bank")

Here, SmartPy automatically determines and remembers that name is a variable that has string data type

Quiz Time:

Just to practice what you learnt above:

In Cryptobot contract shown to your right, what is the data type of name that SmartPy will automatically infer?

When you’re finished:

  1. Click on “Check” to check your submission with the correct answer.
  2. Click on “Show Answer” in case you get stuck.