Test python property not accessible from a staticmethod or classmethod


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()

Is a parammeter a reference to the original variable?


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


blurg
blurg
blarg
blurg
{'ping': 'pong'}
{'ping': 'pong'}
blarg
{'ping': 'pong'}

Let's try to explore generator expresssion and see what we can do with them


In [2]:
generator = (x for x in xrange(10))
print generator.next()
print generator.next()
print generator.next()


0
1
2

Bitwise operators tests


In [5]:
x = 1001
print x & 1

x = 1002
print x & 1

x = 1003
print x & 1


1
0
1

Remplacer le nom de champs d'un namedtuple


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


testY(fieldC='A', fieldD='B')

Remplacer le nom d'un champs de namestuple (essai #2)


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


<class '__main__.testX'>
Out[16]:
__main__.testX

List concatenation


In [17]:
list1 = ['a', 'b']
list2 = ['c', 'd']
list3 = list1 + list2
print list3


['a', 'b', 'c', 'd']

Python dict with keys other then string


In [20]:
my_dict = {1: 'a', 2: 'b'}
print my_dict
print my_dict[1]
print my_dict[2]


{1: 'a', 2: 'b'}
a
b

Tuple with repeated element


In [23]:
repeated_list = ("test",) * 10
print repeated_list


('test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test')

Convert part of a UUID to a integer


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)


12 <type 'int'>

Create a generator out of a paginated method


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


<generator object get_clans at 0x03ABF6C0>
0
1
2
3
4
5
6
7
8
9
  • test
  • test2
  • test3

Raise text


In [1]:
raise "test"


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-6c30f4cb6630> in <module>()
----> 1 raise "test"

TypeError: exceptions must be old-style classes or derived from BaseException, not str

Test datetime formating


In [7]:
import datetime
str(datetime.datetime.now().strftime("%x.%X"))


Out[7]:
'06/27/14.08:04:37'

Time the allocation and deletion time of a 10 000 000 * 100 bytes of memory


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()


(151, 0, 0)
Begin: 0
(13, 0, 0)
Allocated: 0
(15, 0, 0)
Deleted: 0
(12, 0, 0)

Test splitting a string with many separators


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)


['daily', '09:00']
['daily']

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


{'test': {'periods4': ['daily', 'weekly', 'infinite'], 'periods2': {'infinite': None, 'daily': 32400, 'weekly': 43200}, 'periods': ['daily', 'weekly', 'infinite'], 'periods3': ['daily(9:00:00)', 'weekly(8:00)', 'infinite']}}
{x: !!timestamp '2014-07-22 07:28:01.072000'}

<type 'int'>
53626
Out[93]:
<module 'datetime' (built-in)>

Try out enum validation


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)


a
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-123-8d9115c6486a> in <module>()
     15 'a' in test
     16 print test[0]
---> 17 print test[3]
     18 
     19 test.is_in(8)

IndexError: tuple index out of range

Test datetime time constructor with default paremeter


In [99]:
import datetime
print datetime.time()


00:00:00

Fun with Colander and deffered


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)})


{'default_date': datetime.date(2001, 11, 3)}
{'date': datetime.date(2001, 11, 3)}

Fun with escaping % character in python format


In [9]:
test = 'I want the modulo to appear in my string %'

import re
escaped = re.sub(r"%", "\\%%", test)

print escaped


I want the modulo to appear in my string \%%

Test python list unpacking


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


['a']
a
['b', 'c']

Testint the exec and eval statements


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


10
20
allo
Hi, my name is z
i'm local
I was morphed!
i'm local
['this is a return']

How to print exception message


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)


['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', 'args', 'message']
Exception message: 'dict' object is not callable
Exception message: 'dict' object is not callable

Converting UUID to string


In [21]:
import uuid

test = uuid.uuid4()

print test


68c1a5d5-dbdb-4421-b7e5-1c1a93f12dcb

Try defaultdict with del. Will it raise on unknown item?


In [22]:
from collections import defaultdict
test = defaultdict()
try:
    del test['a']
except KeyError as e:
    print e


'a'

Decorate a function with wraps without using @decorator syntax


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")


Je fais pipi
Je fais lalala
10

In [47]:
def function(arg):
    pass

print function.__dict__.get('_name__')
print function.__name__


None
function

Fun with ordereddict


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


  File "<ipython-input-82-c07a0aa4eb10>", line 24
    memberships = OrderedDict(zip(ids, lambda: yield []))
                                                   ^
SyntaxError: invalid syntax

fun with lambda


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


2
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]

In [104]:
## Fun with sorted()
list1 = [10, 8, 11]
list2 = [(8, 'a'), (10, 'b'), (11, 'c')]
sorted_list = sorted(list2)
print sorted_list


[(8, 'a'), (10, 'b'), (11, 'c')]

In [4]:
x = 10234234234234234234
type(x)
x = 123
type(x)

if type(x) not in [int, long]:
    print "yeah!"

In [3]:
print range(10)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Dict comprehension with enumeration


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]:
{'MyTag0': 'x',
 'MyTag1': 1,
 'MyTag2': 'titi',
 'MyTag3': 3,
 'MyTag4': 7,
 'MyTag5': 'yep'}

In [2]:
test = ['a']
print(test==[])


False

Eval and escape code


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()}")


{'message': '"'}
{'message': "'"}
{'message': ''}
{'message': '"'}

Datetime, UUID and JSON


In [106]:
from datetime import datetime
import uuid
test = {'now': datetime.now(),
        'you': uuid.uuid4()}

import json
result = json.dumps(test)
print result


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-106-e4278930c97f> in <module>()
      5 
      6 import json
----> 7 result = json.dumps(test)
      8 print result

C:\Python27\lib\json\__init__.pyc in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, sort_keys, **kw)
    241         cls is None and indent is None and separators is None and
    242         encoding == 'utf-8' and default is None and not sort_keys and not kw):
--> 243         return _default_encoder.encode(obj)
    244     if cls is None:
    245         cls = JSONEncoder

C:\Python27\lib\json\encoder.pyc in encode(self, o)
    205         # exceptions aren't as detailed.  The list call should be roughly
    206         # equivalent to the PySequence_Fast that ''.join() would do.
--> 207         chunks = self.iterencode(o, _one_shot=True)
    208         if not isinstance(chunks, (list, tuple)):
    209             chunks = list(chunks)

C:\Python27\lib\json\encoder.pyc in iterencode(self, o, _one_shot)
    268                 self.key_separator, self.item_separator, self.sort_keys,
    269                 self.skipkeys, _one_shot)
--> 270         return _iterencode(o, 0)
    271 
    272 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

C:\Python27\lib\json\encoder.pyc in default(self, o)
    182 
    183         """
--> 184         raise TypeError(repr(o) + " is not JSON serializable")
    185 
    186     def encode(self, o):

TypeError: UUID('9d46d6a8-ba3d-42a4-aef6-068cc5298e3d') is not JSON serializable

datetime, uuid and cPickle


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


(dp1
S'you'
p2
ccopy_reg
_reconstructor
p3
(cuuid
UUID
p4
c__builtin__
object
p5
NtRp6
(dp7
S'int'
p8
L177087453681991039400872019608237929483L
sbsS'now'
p9
cdatetime
datetime
p10
(S'\x07\xde\n\x11\x07\x14\x14\x01\xcc\xf0'
tRp11
s.
{'you': UUID('8539cd90-3cdd-439c-a209-52f1c7d2740b'), 'now': datetime.datetime(2014, 10, 17, 7, 20, 20, 118000)}

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)


x = 10

Fun with kwds


In [4]:
def my_func(**kwds):
    print kwds
    
my_func(**{'a': 1, 'b': 2})
my_func(a=1, b=2)


{'a': 1, 'b': 2}
{'a': 1, 'b': 2}

Fun with in operator


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]:
False

Fun with tuples and dictionaries


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())


['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_asdict', '_fields', '_make', '_replace', 'a', 'b', 'c', 'count', 'index']
('a', 'b', 'c')
[(1,), (2,), (3,)]
{'a': 1, 'c': 3, 'b': 2}

or in a if


In [6]:
x = 'min'
x = 'max'
x = 'nono'

if x == 'min' or x == 'max':
    print "hello"
else:
    print "nono"


nono

Fun with itertools.groupby


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


key: animal
key: vehicle
('vehicle', 'school bus')

Fun with for ... in ... or loop


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


1
2
3
4
10
11
13

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


No arguments:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-9563e47ee7b8> in <module>()
     33 lazy = LazyClan()
     34 print "No arguments:"
---> 35 print lazy.id
     36 print lazy.name
     37 

<ipython-input-25-9563e47ee7b8> in __getattribute__(self, name)
     25         else:
     26             self = Clan(2, 'tata')
---> 27             setattr(self, "clan_id", object.__getattribute__(self, 'id'))
     28             self.clan = self
     29             print "clan created %s" % str(self)

AttributeError: 'Clan' object has no attribute 'clan_id'

Keyword arguments


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)


hello {'x': 1}

In [3]:
":".join(['adafdsaf', ""])


Out[3]:
'adafdsaf:'

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)


1073741824
<type 'int'>
2147483648
<type 'long'>
-18446744073709551616
<type 'long'>
340282366920938463463374607431768211456
<type 'long'>

Fun with time.time


In [5]:
import time

now = time.time()

time.sleep(1)

print time.time() - now
time.sleep(0.5)
print time.time() - now


1.0
1.5

Fun with inspect


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()


instance_method <function instance_method at 0x03B1A1F0>
is function:instance_method True
is method:instance_method False
is class method:instance_method False
is static method:instance_method False
Decoration function  <function instance_method at 0x03B1A1F0>

__module__ __main__
is function:__module__ False
is method:__module__ False
is class method:__module__ False
is static method:__module__ False

static_method <staticmethod object at 0x03B7A130>
is function:static_method False
is method:static_method False
is class method:static_method False
is static method:static_method True
Decoration function  <staticmethod object at 0x03B7A130>

__metaclass__ <class '__main__.MyMeta'>
is function:__metaclass__ False
is method:__metaclass__ False
is class method:__metaclass__ False
is static method:__metaclass__ False

cls_method <classmethod object at 0x03B1DE70>
is function:cls_method False
is method:cls_method False
is class method:cls_method True
is static method:cls_method False
Decoration function  <classmethod object at 0x03B1DE70>
<unbound method MyClass.wrapper>
True
<unbound method MyClass.wrapper>
True
<unbound method MyClass.wrapper>
True
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
instance_method was called
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-c37755eb8d95> in <module>()
     64 test = MyClass()
     65 test.instance_method()
---> 66 test.cls_method()
     67 test.statici_method()

<ipython-input-47-c37755eb8d95> in wrapper(*args, **kwargs)
     11         def wrapper(*args, **kwargs):
     12             print "xxxxxxxxx" * 100
---> 13             result = func(*args, **kwargs)
     14             return result
     15         return wrapper

TypeError: 'classmethod' object is not callable

Fun with class decorator on class


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()


<__main__.MyClassDecorator object at 0x03B08C70>
<class '__main__.MyClass'>
()
{}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-113-eba11aacdcfa> in <module>()
     49         print "static method called!"
     50 
---> 51 test = MyClass()
     52 print test
     53 test.instance_method()

<ipython-input-113-eba11aacdcfa> in __call__(self, *args, **kwds)
      8         print args
      9         print kwds
---> 10         return self.cls(*args, **kwds)
     11 
     12 def my_deco():

<ipython-input-113-eba11aacdcfa> in __init__(self)
     36 
     37     def __init__(self):
---> 38         super(MyClass, self).__init__()
     39 
     40     def instance_method(self):

TypeError: must be type, not MyClassDecorator

In [ ]: