South Africa - Flag South Africa

Incoterms:DDU
Duty, customs fees and taxes are collected at time of delivery.

Please confirm your currency selection:

US Dollars
Free shipping on most orders over $150 (USD)
All major credit cards accepted

Euros
Free shipping on most orders over 150 € (EUR)
All major credit cards accepted

South African Rand
Free shipping on most orders over R2 000 (ZAR)
American Express not accepted as a method of payment

British Pounds
Free shipping on most orders over £150 (GBP)
All major credit cards accepted

Bench Talk for Design Engineers

Bench Talk

rss

Bench Talk for Design Engineers | The Official Blog of Mouser Electronics


Differences Between Python and MicroPython Mike Parks

(Source: Quality Stock Arts - stock.adobe.com)

One of the most appealing aspects of programming in MicroPython is its similarity to the widely popular CPython used on desktop environments for almost two decades. Thanks to the nearly identical syntax and design paradigms, moving between the embedded and desktop development environments can be a virtually seamless experience. This can be highly desirable in the Internet of Things era, where data from embedded electronics products must be accessible on a plethora of platforms, including mobile, desktop, and the cloud. Development staff can be kept lean, and product development cycles tightened if the variation in tools and programming languages are minimized. That said, the very nature of the embedded hardware environment, as compared to desktop computing, necessitates some not insignificant differences between MicroPython and CPython.

The embedded electronics ecosystem is constrained in many ways that desktops or servers are not. First and foremost, they are constrained by energy consumption. Many embedded devices are battery-powered, and thus extending battery life is limited in terms of performance. Desktop computers may operate at several gigahertz, whereas microcontrollers are, at best, operating at speeds measured in the tens of megahertz. Constrained memory and storage also tend to be limiting factors that significantly impact the difference between CPython and MicroPython. With memory measured in mere kilobytes or megabytes, memory-intensive features are often reduced or even completely removed from the MicroPython implementation. Knowing the differences is important for developers who wish to avoid many frustrating hours debugging their embedded code. Here are the crucial differences developers ought to be aware of:

  • CPython developers have access to hundreds of pre-built modules that can be easily added into their projects with a single line of code. These modules eliminate the need to reinvent the wheel when seeking to add functionality to a project. However, many modules can be quite large in terms of memory utilization. MicroPython either eliminates modules or provides tailored implementations of modules designed for embedded platforms. There are also modules unique to embedded platforms, such as interfacing with general-purpose I/O (GPIO) pins.

 

  • CPython uses automatic reference-counting as its means for memory management, whereas MicroPython uses garbage collection. From a practical perspective, when memory needs to be allocated, MicroPython will try to find a sufficiently sized chunk of memory on the heap. Should this fail, MicroPython will look to deallocate unused or redundant objects in memory. This is a process that is typically measured in milliseconds. Alternatively, a developer can occasionally run gc.collect() to clean up memory at predetermined intervals, ensuring garbage collection does not occur during critical sections of code.

 

  • Syntax differences are probably the type of differences that will get most developers into problems, especially if you have any significant experience with CPython that might give you a sort of "muscle memory" while programming.

 

    • MicroPython requires spaces between literal numbers and keywords; CPython, in contrast, does not.

    • MicroPython allows using := to assign to the variable of a comprehension; CPython raises a syntax error.

 

  • One of the design features that makes Python friendly to new coders is how it handles data types (e.g., integer, boolean, float). In Python, all data types are classes, and a variable is an instance of the class. However, MicroPython does not implement the entire CPython object data model. Differences of note include lack of multiple inheritance, the __new__ and __del__special methods may not work, method resolution order is different, and metaclasses are not supported.

 

  • Exception chaining is not implemented in MicroPython. Therefore, MicroPython cannot rethrow exceptions across different abstraction layers of a program.

 

  • Built-in types are handled differently. For example, MicroPython does not support deleting arrays.

 

  • In Python, functions are objects and have a defined set of attributes that can be accessed via a function call. For example, all functions have a built-in attribute __doc__, which returns the docstring defined in the function source code. User-defined attributes for functions are possible in CPython; however, they are not supported in MicroPython. This is done because of memory limitations typically encountered in embedded systems.

 

  • Overriding sys.stdin, sys.stdout, and sys.stderr are not possible. These are the file objects used by the interpreter for standard input, output, and errors. It is how we display text to a user and get input from the user.

 

  • Modules that fail to load are still registered as loaded. This is to make module-handling more efficient. Thus, loading is not wrapped with exception handling. Be sure to test code in a development environment before deploying to a production environment!

 

  • The environ attribute is not implemented. Instead, developers must use the getenv(),putenv(), and unsetenv() methods to set and get environmental variables. Note that the getenv() method only allows one argument to be passed to it.

 

  • The print() function does not check for recursive data structures (e.g., recursive lists) in the same way CPython does. MicroPython does check stack usage, so printing a recursive data structure won't lead to a crash as a result of a stack overflow.

 

  • Error messages for methods may display unexpected argument counts since MicroPython counts "self" as an argument. Ensure that when working with error messages that this fact is kept in mind.

 

  • JSON (JavaScript Object Notation) is a popular data-interchange format used by many IoT end devices to communicate with the cloud efficiently. The MicroPython JSON module does not throw an exception if a JSON object is not serializable.

 

  • The struct module converts between Python values and C structs represented as Python bytes objects. This allows for efficient handling of binary data stored in files or from network connections or serial protocols commonly used by sensors. Unfortunately, the struct.pack(format, v1, v2) function does not check to ensure that it is given the correct number of arguments. This is in contrast to the CPython implementation, which does check the argument count.

 

  • The capability to search for an integer in an array is not implemented. As such, the following code will result in an error:

 

import array as array

a = array.array('i', [1, 2, 3, 4])

print(1 in a)

 

CPython would print false, whereas MicroPython would return a not implemented error message.

 

MicroPython is a powerful yet easy-to-use programming language for developing embedded applications. However, it is limited when compared to the more feature-rich Python implementations that are used for creating desktop and cloud-native applications. Some differences may be remedied in future versions of MicroPython, or new differences may emerge as new features are added to the reference implementation of Python. To check out the latest differences between CPython and MicroPython, be sure to check out MicroPython's official documentation on their website.



« Back


Michael Parks, P.E. is the co-founder of Green Shoe Garage, a custom electronics design studio and embedded security research firm located in Western Maryland. He produces the Gears of Resistance Podcast to help raise public awareness of technical and scientific matters. Michael is also a licensed Professional Engineer in the state of Maryland and holds a Master’s degree in systems engineering from Johns Hopkins University.


All Authors

Show More Show More
View Blogs by Date

Archives