Skip to content

Instantly share code, notes, and snippets.

View domodomodomo's full-sized avatar

domodomodomo domodomodomo

View GitHub Profile
@domodomodomo
domodomodomo / django_random_username.py
Last active January 31, 2018 21:08 — forked from jcinis/gist:2866253
Generate a random username for Django
"""Make a random username for Django, such as 'adf1-2dfa-dfc4-fa9a'."""
import random
import string
from django.contrib.auth import get_user_model
AuthUser = get_user_model()
def make_random_username(length=16,
import timeit
def sample_code():
lst, v = [1, 5, 3, 4, 5, 6, 7, 5, 5, 10], 5
remove_equal(lst, v)
print(lst, v) # [1, 3, 4, 6, 7, 10] 5
def remove_equal_listcomprehension(lst: list, v):
from abc import ABCMeta, abstractmethod
class Len(metaclass=ABCMeta):
@abstractmethod
def len(self):
"""Return length of object."""
raise NotImplementedError()
def checktype(method):
def classmethod(method):
def decorated_method(self, *args, **kwargs):
cls = type(self)
return method(cls, *args, **kwargs)
return decorated_method
def staticmethod(method):
def decorated_method(self, *args, **kwargs):
# self を省略してメソッドを呼び出す。
@domodomodomo
domodomodomo / ids.py
Last active May 18, 2018 05:01
Show object's identity recursively.
"""Show object's identity recursively.
sample code 1 ... difference between copy and deepcopy
sample code 2 ... reason why [[0]*3]*3 is not good for 2d list initialization
"""
def ids(identifier: object) -> dict:
"""Return the “identity” of an object, recursively."""
# Effective Python item 26
def usage():
n = 2**2 * 3**2 * 5**2
print('# n')
print(n)
print('## factorize')
print(factorize(n))
print('## divisor')
for d in divisorize((factorize(n))):
print(d, num(d))
@domodomodomo
domodomodomo / emulating_oop.py
Last active June 6, 2018 02:47
Emulating Object Oriented Programming with dict and function.
"""Emulating Object Oriented Programming with dict and function.
### 0. reference
1) This code was written by refering below content.
Python のクラスシステム - http://www.shido.info/py/python7.html
### 1. emulating 3 concepts, class, instance and method.
1) class -> dict
2) instance -> dict
3) method -> function
@domodomodomo
domodomodomo / immutable_metaclass.py
Last active November 4, 2019 08:02
Make an object immutable without namedtuple.
"""
# 概要
immutable なオブジェクトを生成するメタクラス Immutable
属性参照は速いけど
namedtuple: 0.07781907100070384
自作したクラス: 0.04243788100029633
インスタンス化は遅い
import collections
def sample():
# point 1. 属性はデコレータに文字列で与える。
@immutable(
'x1', 'y1', 'x2', 'y2',
'is_rectangle', 'is_line', 'is_dot')
class Region(object):
# point 2. __init__ ではなく、__new__ を使う。
"""Compare two list."""
def equal_list(lst1, lst2):
lst1 = lst1.copy()
for element in lst2:
try:
lst1.remove(element)
except ValueError:
return False