In [ ]:
# Test python property not accessible from a staticmethod or classmethod
class A(object):
@property
def my_property(self):
return "bonjour"
class B (A):
@staticmethod
def my_static_method():
return B.my_property.__get__('my_property')
@classmethod
def my_class_method(cls):
# return cls.my_property
return cls.my_property.__get__('my_property')
def my_method(self):
return self.my_property
b = B()
print b.my_property
print b.my_class_method()
print b.my_static_method()
print b.my_method()
In [3]:
def test_reference_paramter(my_param):
print my_param
my_param = "blarg"
print my_param
# Test with string
test = "blurg"
print test
test_reference_paramter(test)
print test
# Test with dict (object)
test = {"ping": "pong"}
print test
test_reference_paramter(test)
print test
In [2]:
generator = (x for x in xrange(10))
print generator.next()
print generator.next()
print generator.next()
In [5]:
x = 1001
print x & 1
x = 1002
print x & 1
x = 1003
print x & 1
In [6]:
from collections import namedtuple
testX = namedtuple('testX', 'fieldA fieldB')
testY = namedtuple('testY', 'fieldC fieldD')
instance = testX(fieldA='A', fieldB='B')
# Here is the magic, use the namedtupe internal method `_make` to create the namedtuple from an iterable!
new_instance = testY._make(instance)
print new_instance
In [16]:
from collections import namedtuple
testX = namedtuple('testX', 'fieldA fieldB')
testY = namedtuple('testY', 'fieldC fieldD')
instance = testX(fieldA='A', fieldB='B')
print testX
testX
#instance.fieldC = instance.fieldA
Out[16]:
In [17]:
list1 = ['a', 'b']
list2 = ['c', 'd']
list3 = list1 + list2
print list3
In [20]:
my_dict = {1: 'a', 2: 'b'}
print my_dict
print my_dict[1]
print my_dict[2]
In [23]:
repeated_list = ("test",) * 10
print repeated_list
In [35]:
import uuid
PLAYER_X = 'deadbeef-0000-0000-0000-000000000012'
test = uuid.UUID(PLAYER_X)
converted = int(str(test)[-2:])
print converted, type(converted)
In [39]:
def get_clans(count):
""" Generator to palliate to lack of APIs in the Clans service for this soft of search. """
for start in xrange(0, count, 5):
memberships = range(start, start + 5)
for membership in memberships:
yield membership
print get_clans(10)
for clan in get_clans(10):
print clan
In [1]:
raise "test"
In [7]:
import datetime
str(datetime.datetime.now().strftime("%x.%X"))
Out[7]:
In [18]:
def allocate_blocks():
return [object() for _ in xrange(100)]
#return 100 *#object()#bytearray(100)
def delete_blocks(blocks):
for block in blocks:
del block
import gc
print gc.get_count()
print "Begin: %d" % gc.collect()
print gc.get_count()
blocks = allocate_blocks()
print "Allocated: %d" % gc.collect()
print gc.get_count()
delete_blocks(blocks)
print "Deleted: %d" % gc.collect()
print gc.get_count()
In [97]:
def splitme(text):
# Remove whitespaces
text = text.replace(" ", "")
import re
return re.split('\(|\)|-', text)[:2]
test = "daily ( 09:00) "
print splitme(test)
test = "daily"
print splitme(test)
In [93]:
import yaml
file = open("d:\\downloads\\time.yml", 'r').read()
print yaml.load(file)
import datetime
print yaml.dump({'x': datetime.datetime.now()})
test = yaml.load("14:53:46")
print type(test)
print test
datetime
Out[93]:
In [123]:
class Enum(tuple):
__getattr__ = tuple.index
def as_dict(self):
""" Convert the Enum to a dict"""
return dict([(key, getattr(self, key)) for key in self])
def is_in(self, value):
return 0 < value <= len(self)
test = Enum(['a', 'b'])
'a' in test
print test[0]
print test[3]
test.is_in(8)
In [99]:
import datetime
print datetime.time()
In [122]:
import datetime
import colander
#import deform
@colander.deferred
def deferred_date_missing(node, kw):
default_date = kw.get('default_date')
if default_date is None:
default_date = datetime.date.today()
return default_date
class BlogPostSchema(colander.Schema):
date = colander.SchemaNode(
colander.Date(),
title = 'Date',
missing = deferred_date_missing,
description = deferred_date_description,
validator = deferred_date_validator,
)
class DefaultsSchema(colander.Schema):
default_date = colander.SchemaNode(
colander.Date(),
title = 'Date',
missing = datetime.date.today(),
)
config = {'body': 1, 'category': 'one', 'title': 'my title', 'default_date': datetime.datetime(year=2001, month=11, day=3).isoformat()}
defaults = DefaultsSchema().deserialize(config)
print defaults
schema = BlogPostSchema().bind(
default_date = datetime.date.today(),
)
#config = {'body': 1, 'category': 'one', 'title': 'my title'}
schema = BlogPostSchema().bind(**defaults)
print schema.deserialize(config)
#schema.deserialize({'body': 1, 'category': 'one', 'title': 'my title', 'default_date': datetime.datetime(year=2001, month=11, day=1)})
In [9]:
test = 'I want the modulo to appear in my string %'
import re
escaped = re.sub(r"%", "\\%%", test)
print escaped
In [9]:
test = ['a', 'b', 'c']
# python 3 only: a, *the_rest = test
a = test[:1]
print a
a = test[:1][0]
print a
the_rest = test[1:]
print the_rest
In [53]:
exec "x = 10"
print x
print eval('10 + 10')
def my_func(arg):
print arg
eval("my_func ('allo')")
def test_update():
global z
print z
z = "I was morphed!"
print x
return "this is a return"
z = "Hi, my name is z"
x = "i'm local"
submissions = []
exec "submissions.append(test_update())" in {'z': z, 'test_update': test_update}, {'x': x , 'submissions': submissions}
print z
print x
print submissions
In [20]:
my_dict = {}
try:
my_dict()
except Exception as e:
print dir(e)
print "Exception message: %s" % e.message
print "Exception message: %s" % str(e)
In [21]:
import uuid
test = uuid.uuid4()
print test
In [22]:
from collections import defaultdict
test = defaultdict()
try:
del test['a']
except KeyError as e:
print e
In [43]:
from functools import wraps
def my_function(message):
return message
my_function("caca")
def my_wrapper(func, *args, **kwds):
def wrapper(*args):
print "Je fais " + func(*args)
return 10
return wrapper
my_function = my_wrapper(my_function)
my_function("pipi")
print my_function("lalala")
In [47]:
def function(arg):
pass
print function.__dict__.get('_name__')
print function.__name__
In [82]:
from collections import OrderedDict
from itertools import cycle
test_dict = {'a': 1, 'b': 2, 'c': 3}
print 'Normal dictionary'
print test_dict
print test_dict.items()
for k, v in test_dict.items():
print k, v
test = OrderedDict()
for k, v in sorted(test_dict.items()):
test[k] = v
print 'OrderedDict'
print test
for k, v in test.items():
print k,v
ids = [3, 2, 6]
memberships = OrderedDict(zip(ids, lambda: yield []))
print memberships
print memberships.items()
print dict(memberships)
test = memberships[3]
print test
print type(test)
test.append('a')
test.append('b')
print memberships[3]
print memberships
memberships[3] = memberships
In [94]:
# no parameter
test = lambda: 2
print test()
# generator
def create_list():
for _ in xrange(10):
yield []
for i, x in enumerate(create_list()):
x.append(i)
print x
In [104]:
## Fun with sorted()
list1 = [10, 8, 11]
list2 = [(8, 'a'), (10, 'b'), (11, 'c')]
sorted_list = sorted(list2)
print sorted_list
In [4]:
x = 10234234234234234234
type(x)
x = 123
type(x)
if type(x) not in [int, long]:
print "yeah!"
In [3]:
print range(10)
In [6]:
def create_tags(tag, values):
return {tag + str(i): value for i, value in enumerate(values)}
values = ('x', 1, "titi", 3,7, "yep")
tag = "MyTag"
create_tags(tag, values)
Out[6]:
In [2]:
test = ['a']
print(test==[])
In [103]:
# double quote
metadata = u'{\'message\': \'"\'}'
print eval(metadata)
# single quote
metadata = u"{\"message\": \"'\"}"
print eval(metadata)
# slash
metadata = u'{"message": "\\"}'
decoded_string = metadata.decode('string_escape') # python2
print eval(decoded_string)
metadata = u'{\'message\': \'"\'}'
decoded_string = metadata.decode('string_escape') # python2
print eval(decoded_string)
#print metadata
#print eval(metadata)
def test():
raise Exception("exploded")
#print eval("test()")
#print eval("{'x': test()}")
In [106]:
from datetime import datetime
import uuid
test = {'now': datetime.now(),
'you': uuid.uuid4()}
import json
result = json.dumps(test)
print result
In [108]:
from datetime import datetime
import uuid
test = {'now': datetime.now(),
'you': uuid.uuid4()}
import cPickle
pickled = cPickle.dumps(test)
print pickled
repred = repr(test)
print repred
In [110]:
x = None
x = 'a' if x else x
In [125]:
test = repr("x = 10")
print eval(test)
#test = "open('x.txt')"
#eval(test)
In [4]:
def my_func(**kwds):
print kwds
my_func(**{'a': 1, 'b': 2})
my_func(a=1, b=2)
In [1]:
list_a = ['a', 'b']
list_b = ['a', 'b', 'c', 'd']
list_a in list_b
for elm in list_a:
elm in list_b
Out[1]:
In [12]:
from collections import namedtuple
X = namedtuple("X_", ['a', 'b', 'c'])
test = X(a=1, b=2, c=3)
print dir(test)
print test._fields
print zip(test)
#dict(zip(test))
print dict(test._asdict())
In [6]:
x = 'min'
x = 'max'
x = 'nono'
if x == 'min' or x == 'max':
print "hello"
else:
print "nono"
In [32]:
from itertools import groupby
my_list = [1,2,3,10,11,21,30]
def key(value):
return value%2
#groups = groupby(my_list, key)
#for key, group in groups:
#print "This is the key %s and the group: %s" % (key, str(group))
# print "key: %s" % key
#for result in group:
# print "This is a result %s" % result
things = [("vehicle", "bear"), ("animal", "duck"), ("animal", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
groups = dict(groupby(things, lambda x: x[0]))
for key, group in groups.iteritems():
#print "This is the key %s and the group: %s" % (key, str(group))
print "key: %s" % key
#print "group: %s" % str(group)
for result in group:
print result
In [35]:
a = None
b = [1 ,2 ,3 ,4]
for x in a or b:
print x
a = [10, 11, 13]
for x in a or b:
print x
In [25]:
from collections import namedtuple
Clan = namedtuple('Clan', ('id','name'))
class LazyClan(Clan):
def __new__(self, clan=None, clan_id=None, *args, **kwargs):
if clan is not None:
print "Im returning this %s" % str(clan)
return clan
return super(LazyClan, self).__new__(self, id=None, name=None)
def __init__(self, clan=None, clan_id=None, *args, **kwargs):
self.clan_id = clan_id
self.clan = None
super(LazyClan, self).__init__(self, id=None, name=None)
def __getattribute__(self, name):
# no need to fetch, clan_id is available
if name == 'id' and object.__getattribute__(self, 'clan_id') is not None:
return object.__getattribute__(self, 'clan_id')
clan = object.__getattribute__(self, 'clan')
if clan:
return object.__getattribute__(self, name)
else:
self = Clan(2, 'tata')
setattr(self, "clan_id", object.__getattribute__(self, 'id'))
self.clan = self
print "clan created %s" % str(self)
return object.__getattribute__(self, name)
lazy = LazyClan()
print "No arguments:"
print lazy.id
print lazy.name
lazy = LazyClan(clan=None, clan_id=3)
print "\n\nClan id provided:"
print lazy.id
print lazy
print lazy.name
print lazy
clan = Clan(123, "new clan")
lazy = LazyClan(clan=clan)
print lazy==clan
print "\n\nFull clan provided:"
print lazy.id
print lazy.name
In [11]:
def test(arg1, **kwds):
print arg1, kwds
def test2(arg1, **kwds):
# Note: need to use unpack operator again!
return test(arg1, **kwds)
test2('hello', x = 1)
In [3]:
":".join(['adafdsaf', ""])
Out[3]:
In [17]:
x = 2**30
print x
print type(x)
x = 2**31
print x
print type(x)
y = -2**64
print y
print type(y)
y = 2**128
print y
print type(y)
In [5]:
import time
now = time.time()
time.sleep(1)
print time.time() - now
time.sleep(0.5)
print time.time() - now
In [47]:
from inspect import (
ismethod,
isfunction,
)
from functools import wraps
def profile_duration(name):
def decorator(func):
#@wraps(func)
def wrapper(*args, **kwargs):
print "xxxxxxxxx" * 100
result = func(*args, **kwargs)
return result
return wrapper
return decorator
class MyMeta(type):
def __new__(cls, name, bases, dict):
for k, v in dict.iteritems():
print ""
print k, v
print "is function:" + k, isfunction(v)
print "is method:" + k, ismethod(v)
print "is class method:" + k, isinstance(v, classmethod)
print "is static method:" + k, isinstance(v, staticmethod)
if (
#isfunction(v) or
isinstance(v, classmethod) or
isinstance(v, staticmethod)
):
print "Decoration function ", v
dict[k] = profile_duration(k)(v)
return type.__new__(cls, name, bases, dict)
def __getattr__(cls, name):
print cls, name
return super(MyMeta).__getattr__(cls, name)
class MyClass(object):
__metaclass__ = MyMeta
@classmethod
def cls_method(cls):
print "cls_method was called"
@staticmethod
def static_method():
print "static_method was called"
def instance_method(self):
print "instance_method was called"
print MyClass.cls_method
print ismethod(MyClass.cls_method)
print MyClass.static_method
print ismethod(MyClass.static_method)
print MyClass.instance_method
print ismethod(MyClass.instance_method)
test = MyClass()
test.instance_method()
test.cls_method()
test.statici_method()
In [113]:
class MyClassDecorator(object):
def __init__(self, cls):
self.cls = cls
def __call__(self, *args, **kwds):
print self
print self.cls
print args
print kwds
return self.cls(*args, **kwds)
def my_deco():
# define the decorator function that acts on the actual class definition
def decorator(*args, **kwds):
# do something here with the information
#print name, cls
print cls, args, kwds
#setattr(cls, name, 'Hello world!')
# return the original, augmented class
return cls #(*args, **kwds)
# return the decorator to act on the class definition
return decorator
class A(object):
pass
@MyClassDecorator
#@my_deco("test")
#@my_deco
class MyClass(A):
def __init__(self):
super(MyClass, self).__init__()
def instance_method(self):
print "instance method called!"
@classmethod
def class_method(cls):
print "class method called!"
@staticmethod
def static_method():
print "static method called!"
test = MyClass()
print test
test.instance_method()
test.class_method()
test.static_method()
In [ ]: