Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Dec 24, 2020

[python3] s.isdigit() vs. s.isnumeric() vs. s.isdecimal()

Reference:


>>> def spam(s):
...     for attr in 'isnumeric', 'isdecimal', 'isdigit':
...         print(attr, getattr(s, attr)())
...         
>>> spam('½')
isnumeric True
isdecimal False
isdigit False
>>> spam('³')
isnumeric True
isdecimal False
isdigit True

Dec 23, 2020

[python3] list vs. deque performance

Question [lc 1032]:
Implement the StreamChecker class as follows:
StreamChecker(words): Constructor, init the data structure with the given words.
query(letter): returns true if and only if for some k >= 1,
the last k characters queried (in order from oldest to newest, including this letter just queried)
spell one of the words in the given list.

Example:

StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
streamChecker.query('a'); // return false
streamChecker.query('b'); // return false
streamChecker.query('c'); // return false
streamChecker.query('d'); // return true, because 'cd' is in the wordlist
streamChecker.query('e'); // return false
streamChecker.query('f'); // return true, because 'f' is in the wordlist
streamChecker.query('g'); // return false
streamChecker.query('h'); // return false
streamChecker.query('i'); // return false
streamChecker.query('j'); // return false
streamChecker.query('k'); // return false
streamChecker.query('l'); // return true, because 'kl' is in the wordlist

Note:
1 <= words.length <= 2000
1 <= words[i].length <= 2000
Words will only consist of lowercase English letters.
Queries will only consist of lowercase English letters.
The number of queries is at most 40000.

Solve:
It's a trie problem. The thought should focus on query.
Thoughts:
  • How to preserve the previous input state?
    stack
  • Could backtrace be faster?
    Yes, only if the words last character being input could consider a hit.
    Thus should build a reverse trie.
  • Tests can up to thousands thus query would be called about that much, Thus the stack used to preserve records could be large enough to trigger a realloc, which is SLOW(copy existing values to new memory address). In Python, instead of using list(which act like C++ vector), use deque to prevent realloc system call. Ref: https://stackoverflow.com/a/23487658


from collections import deque

class StreamChecker:
    def __init__(self, words: List[str]):
        self.trie = {}
        self.stack = deque()

        for word in set(words):
            node = self.trie

            for c in word[::-1]:
                if c not  in node:
                    node[c] = {}
                node = node[c]

            node[None] = None

    def query(self, letter: str) -> bool:
        self.stack.appendleft(letter)

        node = self.trie

        for c in self.stack:
            if None in node:
                return True

            if c not in node:
                return False
            node = node[c]

        return None in node

Aug 13, 2019

[python] object.__contains__(self, item)

[python] some new features in 3.8

Reference:
https://lwn.net/Articles/793818/

walrus operator (:=, like in Go, but also works in 'while' statement):

code:
if m := re.match(p1, line):
        return m.group(1)
elif m := re.match(p2, line):
    return m.group(2)
elif m := re.match(p3, line):
while ent := obj.next_entry():

    ... # process ent

Debug support for f-strings (the format string):

code:
Before 3.8:
print(f'foo={foo} bar={bar}')

In 3.8:
>>> foo = 42
>>> bar = 'answer ...'
>>> print(f'{foo=} {bar=}')
foo=42 bar=answer ...

"!s" uses the str() representation, rather than the default repr() value:

code:
>>> import datetime
>>> now = datetime.datetime.now()
>>> print(f'{now=} {now=!s}')
now=datetime.datetime(2019, 7, 16, 16, 58, 0, 680222) now=2019-07-16 16:58:00.680222

"!f" will be available to access formatting controls:

code:
>>> import math
>>> print(f'{math.pi=!f:.2f}')
math.pi=3.14

Positional-only parameters:

Before 3.8 we can't make a pure python function likes the built-in ones
which disallows keyword arguments.

In 3.8, the "/" denotes the end of the positional-only parameters in an argument list.

code:
def fun(a, b, /, c, d, *, e, f):
thus:
fun(1, 2, 3, 4, e=5, f=6)          # legal
fun(1, 2, 3, d=4, e=5, f=6)        # legal
fun(a=1, b=2, c=3, d=4, e=5, f=6)  # illegal

A movable __pycache__:

__pycache__ directory is created by the Python 3 interpreter (starting with 3.2) to hold .pyc files.

PYTHONPYCACHEPREFIX environment variable (also accessible via the -X pycache_prefix=PATH command-line flag) to point the interpreter elsewhere for storing those files.

Jul 11, 2019

[python] hint of reducing a bit of type instance's memory allocated

Reference:
https://habr.com/en/post/458518/
http://book.pythontips.com

Take away:
Use __slots__ if possible.
http://book.pythontips.com/en/latest/__slots__magic.html

__slots__ has been around for a while; however seldom being used in
codes, which is a good practice for limiting the fields being added to type instance dynamically during runtime.

Reason of taking less memory: it's like __slots__ vs. __dict__, which the later data structure consumes more book-keeping info then simply a continuous array.

Sep 25, 2018

[C++][CppCon 2018] Concepts is NOW.

Why even though current day job aren't anything about C++ but still coding side projects with it?

Because, it's about logic, math, fundamental computer science and speed. [advanced 'C', close to hardware, abstract with mathematical proofs]

Reference:


Type:
  • Specifies the set of operations that can be applied to an object  
    • implicitly and explicitly
    • relies on function declaration and language rules
  • Specifies how an object is laid out in memory
Concept:
  • Specifies the set of  operations that can be applied to an object.
    • implicitly and explicitly
    • relies on use patterns
  • Reflecting function declarations and language rules
  • Says nothing about the layout of the object


The fundamental is function overloading.
The fundamental of the fundamental is: name mangling :-)

Concepts:
Pros:
  • Better design
  • Readability, maintainability
  • Overloading
  • Fewer traits (duh~ brain teasing~)
 
Cons:
  •     I'll give it a try with examination.
 
Syntax Keywords:
requires (expression)

Concepts act as type for variable declaration:
Input_channel ch = foobar();

e.g
template<InputIterator Iter, typename Value>
    requires EqalityComparable<Value_type<Iter>, Value>
Iter find(Iter first, Iter last, Value val);

Golang doesn't support generic, thus we can see
in 'sort' package it uses 'interface' with member function
as contracts to sort data and Search takes a closure to capture
data structure that needs to be searched with a binary search.
Like python's bisect module, with strong type.

Apr 10, 2018

[LC][programming][algorithm] tilde operator

https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python


def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) / 2)) 
LC48:
class Solution:
    def rotate(self, A):
        n = len(A)
        for i in range(n/2):
            for j in range(n-n/2):
                A[i][j], A[~j][i], A[~i][~j], A[j][~i] = \
                         A[~j][i], A[~i][~j], A[j][~i], A[i][j]


LC: 246
class Solution(object):
    def isStrobogrammatic(self, num):
        """
        :type num: str
        :rtype: bool
        0 0  不能為第一個.
        1 1
        6 9
        9 6
        8 8
        """
        from __builtin__ import xrange

        dmap = dict((('0', '0'), ('1', '1'), ('6', '9'),
                     ('9', '6'), ('8', '8')))

        if num[0] == '0' and len(num) > 1:
            return False

        if len(num) % 2:
            # corner cases
            if num[len(num) / 2] not in ('0', '1', '8'):
                return False

        for i in xrange(len(num) / 2):
            if num[i] not in dmap or num[~i] != dmap[num[i]]:
                return False

        return True

Apr 6, 2018

[python] str concatenation.

https://stackoverflow.com/questions/1316887/what-is-the-most-efficient-string-concatenation-method-in-python

https://stackoverflow.com/questions/39622122/python-string-concatenation-in-for-loop-long-strings

It's interesting that, in python2.x

str += str2 is faster then "".join((str, str2))

in python3, the later is faster.

However, the memory usage hasn't been counted in above methods.

Guess?

I would say "".join would probably using less memory due to a hunch from c++ background,
still, profiling instead of guessing :-P

May 16, 2017

[python][twisted][original][note] Twisted really so twisted? The essence of deferred object.

Purpose of this article

  • Understand Deffered class 
  • Know how inlineCallbacks decorator works 
  • How these enable async code flow

Time of reading: 27 mins

Deffered Class

Deffered class is designed with Fluent interface (https://en.wikipedia.org/wiki/Fluent_interface#Python)
which enables the use of @inlineCallbacks.

Example code of Fluent interface:

class FluentPerson(object):
    def run(self):
        print("run\n")
        return self
    def jump(self):
        print("jump\n")
        return self
    def walk(self):
        print("walk\n")
        return self
         
if __name__ == "__main__":
    """prints:
        run
        jump
        walk
    """
    FluentPerson().run().jump().walk()


Deferred Object
Deffered type

4 major member functions
  • addCallback(self, callback, *args, **kw)
  • addErrback(self, errback, *args, **kw)
  • callback(self, result)
  • errback(self, fail=None)
Example
from twisted.internet.defer import (                                           
    Deferred)                                                                  
                                                                                 
                                                                                 
def callback(result, arg_1):                                                   
    """                                                                        
    :param result: argument passed by Deffered.callback(arg)                   
    :param arg_1: as argument passed in by Deffered.addCallback()              
    """                                                                        
    print(result)                                                              
    print(arg_1)                                                               
                                                                                 
                                                                                 
def errcallback(result, arg_1):                                                
    """                                                                        
    :param result: argument passed by Deffered.errback(arg), which will be wrapped in Failure instance.              
    :param arg_1: as argument passed in by Deffered.addErrback()              
    """                                                                        
    print(result)                                                              
    print(arg_1)
     
     
if __name__ == "__main__":                                                     
    """                                                                        
    Print:                                                                     
    42                                                                         
    arg_1                                                                      
    """                                                                        
    d = Deferred()                                                             
    d.addCallback(callback, "arg_1")                                           
    d.callback(42)                                                             
                                                                                 
    # Can not call .callback or errback more than once.                        
    """                                                                        
    Print:                                                                     
    [Failure instance: Traceback (failure with no frames): class twisted.python.failure.defaultexception="": Test fail.                     
    ]                                                                          
    arg_1                                                                      
    """                                                                        
    d = Deferred()                                                             
    d.addErrback(errcallback, "arg_1")                                                                               
    d.errback("Test fail.") # If without Argument, a real exception should have been throwed.

@inlineCallbacks decorator

This is where light weight thread(green thread) begins.

Idea


Utilizing python yield(aka. generator/coroutine) with deferred object to create async programming.

Something about python 'yield'

  • yield is an expression, which will be evaluated during runtime.(i.e not compile time)
  • generator.send(None) will trigger the generator, same as calling next(generator)
  • a generator won't be triggered to run until we call generator.send(None) or next(generator)
  • the left hand side equation of yield expression will get the value from caller calling generator.send(VALUE).

Above four concepts are important for us to understand how inlineCallbacks works.
(and how it's implemented.)
inlineCallbacks

Example
#!/bin/env python                                                              
def returnVal():                                                                                                     
    print("step_2")                                                            
    return 42                                                                  
                                                                                 
                                                                                 
def yieldfunc():                                                               
    result = yield returnVal()  # generator stops here on the right hand side of equation until caller calls .send(VALUE)                                      
    print(result)                                                              
                                                                                 
                                                                                 
if __name__ == "__main__":                                                     
    """                                                                        
    Print:                                                                     
        step_0                                                                 
        step_1                                                                 
        step_2                                                                 
        step_3                                                                 
        42                                                                     
        None                                                                   
        ---                                                                    
        step_2                                                                 
        42                                                                     
        None                                                                   
    """
    print("step_0")                                                            
    g = yieldfunc()                                                            
    print("step_1")                                                            
    # yieldfunc's yield returnVal() won't be evaluated till g.send(None)       
    # being called.                                                            
    result = g.send(None)                                                      
    print("step_3")                                                            
                                                                                 
    print(result)                                                              
                                                                                 
    try:                                                                       
        """                                                                    
        Last call to generator will throw StopIteration exception.             
        However, if using 'for' loop, it will catch StopIteration exception    
            for us.                                                            
        """                                                                    
        g.send(None)                                                           
    except StopIteration as e:                                                 
        pass                                                                   
                                                                                 
    print("-" * 3)                                                             
    # call it again using for loop, no need to catch StopIteration exception.  
    g = yieldfunc()                                                            
    for r in g:                                                                
        print(r)



The power of @inlineCallbacks

The @inlineCallbacks decorated generator function will return deferred object.
Thus, it allows the chaining of deferred objects through this fluent interface design.
(If remember how key_monad is designed, it's the same idea.)

Example:
#!/bin/env python                                                               
from twisted.internet.defer import (                                            
    inlineCallbacks, returnValue)                                              
                                                                                 
                                                                                 
@inlineCallbacks                                                               
def begin():                                                                   
    result = yield 42                                                          
    returnValue(result)                                                        
                                                                                 
                                                                                 
if __name__ == "__main__":                                                     
    """                                                                        
    Print:                                                                     
        42                                                                                                           
    """                                                                        
    deferred = begin()                                                         
    print(deferred.result)

Above code Explained



So how does these add up?

Consider replacing
yield 42
with yielding another deferred object...

And when the last of the deferred object chain's deferred object being called .callback(VALUE)
which will trigger a chain reaction(like function recursive call stack rewinds) by poping
up the 'VALUE' up to the chained deferred objects.

And consider the last deferred object's .callback will be called through epoll.

But wait,
You should argue how this becomes an async call, shouldn't the chain of reaction a blocking call
until epoll has the value returned? Bunch of blocking calls layer by layer?


The magic comes from closure and yield.
https://github.com/twisted/twisted/blob/twisted-16.5.0/src/twisted/internet/defer.py#L1316

That is, each deferred object has the references to it's parent's deferred object's generator
and deferred object.

While child's deferred object has yielded a result, we'll call parent's generator's .send()
to send the result to the left hand side of yield expression.

Since the caller already has the parent's deferred object instance, which the code carries on
the workflow(unblocking), until the epoll trigger the child's result will the parent's deferred object's .callback() being called.

If we had registered callback functions to parent's deferred object,
when epoll has return value from child deferred object,
the parent's registered callback functions will be called with the result.

There's another trick to check if the child has the .callback() being called is that
to check parent's deferred object has data member ".result" or not.
(Not recommended.)

Here the example code for this chain reaction:
#!/bin/env python                                                                                                    
import time                                                                    
import threading                                                               
                                                                                 
from twisted.internet.defer import (                                           
    Deferred, inlineCallbacks, returnValue)                                    
                                                                                 
                                                                                 
@inlineCallbacks                                                               
def begin(defer):                                                              
    """                                                                        
    The most outter defer instance.                                            
    It's chaining the defer instances to the end.                              
    If there's no result from chainning defer instances, simply return a       
    un-called defer instance back to caller.                                   
    """                                                                        
    result = yield defer                                                       
                                                                                 
    """                                                                        
    The result would be the chained defer instances' result.                   
    """                                                                        
    returnValue(result)                                                        
                                                                                 
 
def thread_run():                                                              
    """                                                                        
    This thread function mimic epolling.                                       
    While there's a result from epoll, call the most end defer instance, and   
    triggers a chain reaction all the way back to the outtermost caller.       
    """                                                                        
    time.sleep(3)                                                              
    stand_alone_defer.callback(42)                                             
                                                                                 
                                                                                 
def collect(result):                                                           
    global called                                                              
    called = True                                                              
    # Must return the result for continuous call.                              
    return result
     
if __name__ == "__main__":
    """                                                                        
    Print:                                                                     
        waiting...                                                             
        waiting...                                                             
        waiting...                                                             
        waiting...                                                             
        waiting...                                                             
        waiting...                                                             
        waiting...                                                             
        Got outter most defer instance's result: 42                                                                  
    """
    global stand_alone_defer                                                   
    global called                                                              
    called = False                                                             
                                                                                 
    stand_alone_defer = Deferred()                                             
    stand_alone_defer.addCallback(collect)                                     
                                                                                 
    result = begin(stand_alone_defer)                                          
                                                                                 
    thread = threading.Thread(                                                 
        name="run deferred's callback", target=thread_run)                     
    thread.start()                                                             
                                                                                 
    while not called:                                                          
        print("waiting...")                                                                                          
                                                                                 
    thread.join()                                                              
                                                                                 
    print("Got outter most defer instance's result: {0}".format(result.result))

Apr 21, 2017

[python] metaclass flow

#!/bin/env python


class MetaType(type):

    def __new__(cls, name, bases, attrs):
        print("in meta new")
        print("name: " + name)
        print("bases: " + str(bases))
        print("attrs: " + str(attrs))
        print("klas info: " + str(cls.__class__))
        #  return type(name, bases, attrs)
        #  Above code will lose metatype info,
        #  which De will be built by 'type', not this MetaType.
        return type.__new__(cls, name, bases, attrs)

    def __init__(cls, name, bases, attrs):
        # cls is returned by this def __new__
        print("in meta init")
        print(dir(cls))

    def __call__(cls, *args, **kwargs):
        print("In meta call")
        # will call type instance's __new__ and __init__
        instance = type.__call__(cls, *args, **kwargs)
        return instance


class Base(object):
    __metaclass__ = MetaType

    def __new__(cls):
        print("in base new")
        print(cls.__class__)  # Print MetaType
        return super(Base, cls).__new__(cls)

    def __init__(self, opt):
        print("Base init")


class De(Base):

    def __new__(cls, input):
        print("in De new")
        print(cls.__class__)  # Print MetaType
        #  return super(Base, cls).__new__(cls) # will bypass Base's __new__
        return super(De, cls).__new__(cls)

    def __init__(self, input):
        print("De init")

    def testFunc(self):
        pass


if __name__ == "__main__":
    """
    1. Constructing Base type instance.
    2. Call MetaType __new__, must return with type.__new__, otherwise using
        type(...) with lose the metaclass info.
    3. Call MetaType __init__
    4. Call MetaType __new__, must return with type.__new__, otherwise using
        type(...) with lose the metaclass info.
        This time with 'De's info.
    5. Call MetaType __init__
    6. Since we call De("hi"), now call MetaType's def __call__
        inside it should call type.__call__ to trigger
        calling MetaType's instance's(aka. De) __new__ and __init__
    7. De's __new__ should call super in order to trigger base instance's
        __new__
    8. De's __init__ should call super in order to trigger base instance's
        __init__
    """
    a = De("hi")

-----------
in meta new
name: Base
bases: (<type 'object'>,)
attrs: {'__module__': '__main__', '__metaclass__': <class '__main__.MetaType'>, '__new__': <function __new__ at 0x7fe775497c80>, '__init__': <function __init__ at 0x7fe775497cf8>}
klas info: <type 'type'>
in meta init
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
in meta new
name: De
bases: (<class '__main__.Base'>,)
attrs: {'__module__': '__main__', 'testFunc': <function testFunc at 0x7fe775497e60>, '__new__': <function __new__ at 0x7fe775497d70>, '__init__': <function __init__ at 0x7fe775497de8>}
klas info: <type 'type'>
in meta init
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'testFunc']
In meta call
in De new
<class '__main__.MetaType'>
in base new
<class '__main__.MetaType'>
De init

Jan 4, 2017

[python] difference between type(), type.__new__()

difference between type(), type.__new__()


>>> class MetaA(type):
...     def __new__(cls, name, bases, dct):
...         print 'MetaA.__new__'
...         return type(name, bases, dct)
...     def __init__(cls, name, bases, dct):
...         print 'MetaA.__init__'
... 
>>> class A(object):
...     __metaclass__ = MetaA
... 
MetaA.__new__
>>> class MetaA(type):
...     def __new__(cls, name, bases, dct):
...         print 'MetaA.__new__'
...
...         # type.__new__() will call MetaA's __init__ to initialize it
...         return type.__new__(cls, name, bases, dct)
...     def __init__(cls, name, bases, dct):
...         print 'MetaA.__init__'
... 
>>> class A(object):
...     __metaclass__ = MetaA
... 
MetaA.__new__
MetaA.__init__

Oct 28, 2016

[python] subprocess block/unblock call

Blocking and Non Blocking subprocess calls

nonblocking: Popen (calling its wait or communicate method to make the call wait/block)
blocking: call , check_call

Strictly speaking, shell=True is orthogonal to the issue of blocking. However, shell=True causes Python to exec a shell and then run the command in the shell. If you use a blocking call, the call will return when the shell finishes. Since the shell may spawn a subprocess to run the command, the shell may finish before the spawned subprocess. For example,

import subprocess
import time

proc = subprocess.Popen('ls -lRa /', shell=True)
time.sleep(3)
proc.terminate()
proc.wait()

Here two processes are spawned: Popen spawns one subprocess running the shell. The shell in turn spawns a subprocess running ls.
proc.terminate() kills the shell, but the subprocess running ls remains.
(That is manifested by copious output, even after the python script has ended.
Be prepared to kill the ls with pkill ls.)

Aug 27, 2016

[python] monad constructor


  def apply_func(monad):
      return monad.result

  def monad_constructor(f):
      """
      type constructor
      1. log
      2. build monad type
      """
      LOG = "Function: {func_name}, Status: {status}, Message: {message}"
      APPLY_FUNC = apply_func
      message = "testing message."

      @functools.wraps(f)
      def wrap(*args, **kargs):
          try:
              result = f(*args, **kargs)
              if result:
                  wrap.result = result
                  wrap.success = True
                  wrap.status = "OK."
              else:
                  wrap.result = None
                  wrap.success = False
                  wrap.status = "Failed."
          except Exception as e:
              wrap.result = str(e)
              wrap.success = False
              wrap.status = "Failed."
          finally:
              wrap.apply = APPLY_FUNC
              wrap.log_msg = LOG.format(
                  func_name=f.__name__,
                  status=wrap.status,
                  message=message)
      return wrap

@monad_constructor
  def none_func():
      """None function
      :return: bool
      """
      return True

@monad_constructor
  def set_log(monad):
      """Setup log
      :param monad: function as monad
      :return: bool
      """
      raise Exception("set log failed")

@monad_constructor
  def access_xen(monad):
      return auth_info


@monad_constructor
  def check_xen_status(monad):
      xen_auth = monad.apply(monad)
      #...
      

def main():
    none_func()
    set_log(none_func)
    access_xen(set_log)
    check_xen_status(access_xen)


if __name__ == "__main__":
      try:
          main()
      except KeyboardInterrupt:
          exit(1)

Jul 22, 2016

[python][twisted] how defer works

twisted inlineCallbacks

from twisted.internet.defer import inlineCallbacks
from twisted.internet.defer import Deferred
from twisted.internet import defer


@inlineCallbacks
def got():
    x = yield 'k22'
    defer.returnValue(x)


@inlineCallbacks
def run():
    print("in run")
    result = yield got()
    print("after yield")
    # print(next(result))
    print("in run's result: {0}".format(result))
    defer.returnValue("return 42")


if __name__ == "__main__":
    print("Start in main")
    result = run()
    print("End after run")
    print("Result: {0}".format(result))
    print(result.result)

May 27, 2016

[python] bound function got ya.

class MetaType(type):
    def __getattribute__(cls, field):
        print("Class name: {0}".format(cls))
        print("Field name: {0}".format(field))
        return type.__getattribute__(cls, field)


class Base(object):
    __metaclass__ = MetaType

    def function(cls):
        print("Class:{0}".format(cls))
    function = classmethod(function)


class Derived(Base):
    pass

if __name__ == "__main__":
    tmp_function = Base.function
    Derived.function()
    print(Derived.function)  # this function is Derived bound function
    Base.function = tmp_function
    Derived.function()
    print(Derived.function)  # this function is Base bound function

May 5, 2016

[python] metaclass used to create derived type instance.

Reference:
http://stackoverflow.com/a/6581949

Python does the following:


  • Is there a __metaclass__ attribute in Foo?
  • If yes, create in memory a class object (I said a class object, stay with me here), with the name Foo by using what is in __metaclass__.
  • If Python can't find __metaclass__, it will look for a __metaclass__ at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).
  • Then if it can't find any __metaclass__ at all, it will use the Bar's (the first parent) own metaclass (which might be the default type) to create the class object.
  • Be careful here that the __metaclass__ attribute will not be inherited, the metaclass of the parent (Bar.__class__) will be. 
    • If Bar used a __metaclass__ attribute that created Bar with type() (and not type.__new__()), the subclasses will not inherit that behavior.


"""
Metaclass code explain
"""


class ModelMeta(type):
    def __new__(cls, name, bases, attrs):
        print("in new")
        print(name)  # Test2
        print(bases)  # (<class '__main__.Test'>,)
        print(cls)  # <class '__main__.ModelMeta'>

        """
        If not using type.__new__, derived class won't use
        metaclass to create type instance.
        """
        result = type.__new__(cls, name, bases, attrs)
        # result = type(name, bases, attrs)
        print(dir(result))
        """
            ['__class__', '__delattr__', '__dict__', '__doc__',
            '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__',
            '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
            '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
        """
        print(result.__metaclass__)  # <class '__main__.ModelMeta'>
        return result

    def __call__(cls, *args, **kwargs):
        print("in call")
        print(cls)
        instance = type.__call__(cls, *args, **kwargs)
        return instance


class Test(object):
    __metaclass__ = ModelMeta


class Test2(Test):
    pass


class Test3(Test2):
    pass

if __name__ == "__main__":
    t2 = Test2()  # call ModelMeta. __call__






Another perspect

"""
Metaclass code explain
"""


class ModelMeta(type):
    def __new__(cls, name, bases, attrs):
        print("in new")
        print("name:{0}".format(name))  # Test2
        print("bases:{0}".format(bases))  # (<class '__main__.Test'>,)
        print("cls:{0}".format(cls))  # <class '__main__.ModelMeta'>
        print("attrs:{0}".format(attrs))  # <class '__main__.ModelMeta'>
        # Class Test 將擁有空的bases集合
        parents = [b for b in bases if isinstance(b, ModelMeta)]
        print("parents:{0}".format(parents))
        """
        If not using type.__new__, derived class won't use
        metaclass to create type instance.
        """
        result = type.__new__(cls, name, bases, attrs)
        # there will be no inheritence affect if using simply type constructor
        # result = type(name, bases, attrs)
        print(dir(result))
        """
            ['__class__', '__delattr__', '__dict__', '__doc__',
            '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__',
            '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
            '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
        """
        print(result.__metaclass__)  # <class '__main__.ModelMeta'>
        return result

    def __call__(cls, *args, **kwargs):
        print("in call")
        print(cls)
        instance = type.__call__(cls, *args, **kwargs)
        return instance


class Test(object):
    __metaclass__ = ModelMeta
    aa = 1


class Test2(Test):
    a = 2


class Test3(Test2):
    a = 3

if __name__ == "__main__":
    t2 = Test2()  # call ModelMeta. __call__
    print(t2.a)

Mar 31, 2015

[C++11/14] gap between exit releasing resource and other thread still running

Darn python bug while calling exit in signal handler.


#include <iostream>
#include <thread>

#include <signal.h>

using namespace std;


void handler(int)
{
    cout << "boom~" << endl;
    exit(42);
}


void _set_handler(int sig)
{
    struct sigaction sact;
    sact.sa_handler = &handler;
    sigaction(sig, &sact, nullptr);
}


template<typename... I>
void set_handler(I... signals)
{
   [](...){}( (_set_handler(signals),0)... );
}


struct ThisIsAType
{
    int a_{42};

    ~ThisIsAType()
    {
        a_ = 0;
        cout << "Destructor fires" << endl;
    }
};


ThisIsAType a_type{};


void runme()
{
    while(true)
    {
        cout << a_type.a_ << endl;
    }
}


int main()
{
    set_handler(SIGTERM, SIGINT);

    thread t1{runme};
    t1.detach();

    while(true)
        continue;
}