Skip to content

Instantly share code, notes, and snippets.

import re
_camelcase_re = re.compile(r'([A-Z]+)(?=[a-z0-9])')
def camel_to_snake_case(name):
def _join(match):
word = match.group()
if len(word) > 1:
return ('_%s_%s' % (word[:-1], word[-1])).lower()
@geekKeen
geekKeen / absolute-import.py
Created July 8, 2017 14:49
Python absolute import
```
file sqlalchemy/orm/mapper.py
```
from __future__ import absoute_import
from collections import deque
class Meta(type):
def __init__(cls, classname, base, fields):
super(Meta, cls).__init__(classname,base, fields)
print cls, classname, base, fields # <class A>, A, <type object>, {...., '__init__': function<...>}
class A(object):
__metaclass__ = Meta
def __init__(self):
pass
from flask import g
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = connect_to_database()
return db
@app.teardown_appcontext
def teardown(exception):
class Object(object):
def __new__(cls, *args, **kwargs):
base = kwargs.pop('base')
instance = super(Object, cls).__new__(base)
instance.initalize(*args, **kwargs)
return instance
class A(Object):
def initalize(self, *args, **kwargs):
@geekKeen
geekKeen / init.py
Created August 1, 2017 15:21
遇到初始化时碰到的一些问题
class A(object):
def __init__(self, **config):
self._config = {}
self.make_config(config)
def make_config(config):
self._config.update(config)
class B(object):
def __init__(self, **config):
@geekKeen
geekKeen / descripter.py
Last active December 25, 2017 03:55
Python 描述符以及property
class Integer(object):
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self, instance, value):
@geekKeen
geekKeen / setattr.py
Created August 16, 2017 03:54
操作属性字典
class A(object):
def __setattr__(self, attr, value):
self.__dict__(self, attr, value) # setattr(self, attr, value)
def __getattr__(self, attr):
return self.__dict__(self, attr) # getattr(self, attr)
@geekKeen
geekKeen / call.py
Created August 21, 2017 07:51
__call__ 函数的使用
class NoInstance(type):
def __call__(self, *args, **kwargs):
raise TypeError('Cannot instantiate directly')
class Spam1(object):
__metaclass__ = NoInstance
class Spam2(object):
def __call__(self, *args, **kwargs):
raise TypeError('Cannot instantiate directly')
@geekKeen
geekKeen / dispatch.py
Created August 23, 2017 09:39
当遇到switch-case 时 处理的技巧, 符合开放封闭原则, 以functions 中singledispath 为例
from functions import singledispatch
@singledispatch
def my_func(args):
print('default myfunc({!r})'.format(arg))
@my_func.register(int)
def my_func(args):
print('myfunc_int({})'.format(arg))