Code Snippet

平时在写代码的过程中经常会使用的代码片段记录在这个地方,方便自己的查找~

Python 中通过元类实现数据类型

参考Panda-Sandbox中实现数据类型

import abc


class Type(metaclass=abc.ABCMeta):
    """ Base Class for Panda-Sandbox Type Definitions """

    __doc__ = """
    Must Implement this class for subtype to create new instance.
    Initialise its with params:
    :param default::默认值
    :param allow_empty::可取空
    @Must implement with below methods:
    :method parse::转化
    :method check::校验
    """

    def __init__(self, default=None, allow_empty=False):
        self.default = default
        self.allow_empty = allow_empty

        self._value = None

    def __set__(self, instance, value):
        if self.check(value):
            self._value = value
        else:
            self._value = self.parse(value)

    def __str__(self):
        if not self._value:
            return str(self.default)
        return str(self._value)

    @abc.abstractmethod
    def parse(self, value):
        """ parse a raw input value to correct type value and locate in the value range """

    @abc.abstractmethod
    def check(self, value):
        """ check the type of a raw value whether we need this type in this instance """

Python 中实现线程单例的方式
import threading


class ThreadSingleton(type):
    """Singleton per thread."""
    _instances = threading.local()

    def __call__(cls, *args, **kwargs):
        if not getattr(cls._instances, "instance", None):
            cls._instances.instance = super(ThreadSingleton, cls).__call__(*args, **kwargs)
        return cls._instances.instance

Python 中实现单例的方式

参考 stackoverflow


class Singleton(type):
    """ Instance Singleton """
    _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]