Monday 21 March 2022

pyenv install 3.9 BUILD FAILED (OS X 12.0.1 using python-build 20180424)

# Install x86 homebrew

arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

alias ibrew="arch -x86_64 /usr/local/bin/brew"


# Install Python 3.9

$ brew install python@3.9


from: https://qiita.com/tsuu/items/50e09d64f5afb5f5b827

Wednesday 16 March 2022

Python: make a derived class into a singleton (Abstract method)

My Code:

# singleton.py
class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

# base.py
from abc import ABC, abstractmethod

class Base(ABC):
    @abstractmethod
    def run(self, value):
        pass

# foo.py
from base import Base
from singleton import Singleton

class Foo(Base, metaclass=Singleton):
    def run(self, value):
        print(value)

# main.py
from foo import Foo

f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2) 

f2.run(24) 

As the error text already says, the metaclass of Foo must be a metaclass that is compatible with the base class metaclass (=ABCMeta). This means that Singleton must also inherit from ABCMeta.

New Code:

# singleton.py

from abc import ABCMeta

class Singleton(ABCMeta):
    # ...

# bar.py
from base import Base

class Bar(Base):
    def run(self, value):
        print(value)

# main.py
from foo import Foo
from bar import Bar

f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2)
f2.run(34)

b1 = Bar()
print(b1)
b1.run(12)
b2 = Bar()
print(b2)
b2.run(21)

Output:

<foo.Foo object at 0x000001D4D512BE48>
42
<foo.Foo object at 0x000001D4D512BE48>
34
<bar.Bar object at 0x000001D4D512B0B8>
12
<bar.Bar object at 0x000001D4D512BEF0>
21

So Foo is a singleton and Bar isn't.


from: https://stackoverflow.com/questions/63373883/python-make-a-derived-class-into-a-singleton

Saturday 5 March 2022

How to measure elapsed time in Python?

 Measuring time in seconds:

from timeit import default_timer as timer
from datetime import timedelta

start = timer()

# ....
# (your code runs here)
# ...

end = timer()
print(timedelta(seconds=end-start))

Output:

0:00:01.946339


from: https://stackoverflow.com/questions/7370801/how-to-measure-elapsed-time-in-python