intro and newbie questions

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
bitrat
Posts: 41
Joined: Fri Jul 26, 2019 4:13 am

intro and newbie questions

Post by bitrat » Fri Jul 26, 2019 5:13 am

Hi,

I'm not that familiar with Python, and more used to 2 than 3. I'm mostly a C++ engineer with a lot of experience in that.

I have some work to do with MicroPython targeting ESP32 and I'm trying to get up to speed on pythonic techniques for best practice.

I have a couple of specific questions:

1. I've been looking for the correct way to do dependency inversion, and it seems to involve super(), however super and MRO are incomplete in MP, on ESP32 anyway. What is the most robust and simple way to achieve this?

2. I tried some different ways to create read only objects using descriptor mechanisms, such as overriding __setattr__, but also fell upon stony ground. I'd be interested in any general observations on these methods in Python 3 and MicroPython.

3. I'm looking for a simple singleton (an antipattern where I come from :) ). I'd prefer one that behaves like a class, but this one I found on this forum (viewtopic.php?t=5033) looks useful. I'd be interested to hear any suggestions.

Code: Select all

def singleton(cls):
    instance = None
    def getinstance(*args, **kwargs):
        nonlocal instance
        if instance is None:
            instance = cls(*args, **kwargs)
        print(instance, id(instance))
        return instance
    return getinstance

@singleton
class MyClass1():
    def method(self):
        pass
I hope this post is suitable for this location.

Cheers,
Bitrat

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: intro and newbie questions

Post by pythoncoder » Fri Jul 26, 2019 5:46 pm

Read only attributes can be created using the @property decorator. If you don't have a setter, it will be read only. However properties and descriptors aren't very efficient and involve slow lookups. The convention in MicroPython code is to use a method for attribute access.

Code: Select all

    @property
    def value(self):  # Slow read-only access
        return self._value
    def ro_value(self):  # Fast read-only access
        return self._value
    def rw_value(self, v=None):  # Fast r/w access
        if v is not None:
           self._some_value = v
       return self._some_value
Re singletons the thread you quoted covers the way I implement them, but a web search will throw up a number of alternatives.
Peter Hinch
Index to my micropython libraries.

bitrat
Posts: 41
Joined: Fri Jul 26, 2019 4:13 am

Re: intro and newbie questions

Post by bitrat » Thu Aug 08, 2019 9:47 pm

Sorry, I meant to say thanks for this. :-)

Post Reply