MicroPython Identifier Naming Rules

Contents

Introduction

MicroPython is a “slim” version of Python specifically designed with a small footprint to efficiently run on memory constrained microcontrollers.

MicroPython is both a loosely typed and dynamically typed language. Variables are not explicitly declared as with strongly typed languages like C++. Rather, a variable is implicitly declared when first used in a statement. The variable type is determined at runtime.

Naming Rules

The rules for naming variables are simple:

  • The first character must be a letter or an underscore ( ‘_’ )
  • The following characters must only be letters, underscores and digits (0 - 9)
  • MicroPython identifiers and key words are case sensitive
  • MicroPython's set of 33 reserved words cannot be used as variable names
Table 1: Python reserved words
and del global not with
as elif if or yield
assert else import pass False
break except in raise None
class finally is return True
continue for lambda try
def from nonlocal while

The following are all legal Python variable names:

  • Babble
  • _Babble
  • _babble
  • _babble89
  • Babble_Rabble34

These are not legal:

Table 2: Illegally named identifiers
$dollar '$' is not an allowable character
5_dollar Must start with an underscore or a letter
pass This is a Python reserved word
Big Man Spaces (' ') are not legal characters

Open the Mu Editor and click the REPL button. Type the following and note the error returned by the MicroPython interpreter:


$dollar = "Bad identifier name"

The micro:bit responds with: 
Traceback (most recent call last):
  File "<stdin>", line 1
SyntaxError: invalid syntax 
          

For a quick demonstration of Python's case sensitivity copy the following code into the Mu Editor, Save and Flash to the micro:bit. Click the REPL button to see the output.

Example 1

add = 1 + 2 + 3 + 4 + 5
Add = 10 + 20 + 30 + 40 + 50
print("add =", add)
print("Add =", Add)
          
Output:

add = 15
Add = 150
          

Its obvious from this example that add and Add are two different identifiers.