Created
January 14, 2014 03:31
-
-
Save sokrato/8412571 to your computer and use it in GitHub Desktop.
Example advanced Python features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding: utf8 -*- | |
''' | |
Examples of advanced Python features: | |
- metaclass | |
- descriptor | |
- generator/forloop | |
''' | |
from __future__ import print_function | |
import sys | |
if sys.version_info > (3,): # Python 3 | |
exec(''' | |
def exec_in(code, glob, loc=None): | |
if isinstance(code, str): | |
code = compile(code, '<string>', 'exec', dont_inherit=True) | |
exec(code, glob, loc) | |
''') | |
exec_in(''' | |
def with_meta(cls): | |
class Meta(metaclass=cls): | |
pass | |
return Meta | |
''', globals()) | |
else: | |
exec(''' | |
def exec_in(code, glob, loc=None): | |
if isinstance(code, str): | |
code = compile(code, '', 'exec', dont_inherit=True) | |
exec code in glob, loc | |
''') | |
exec_in(''' | |
def with_meta(cls): | |
class Meta(object): | |
__metaclass__ = cls | |
pass | |
return Meta | |
''', globals()) | |
class AnimalMeta(object): | |
species = 0 | |
def __new__(cls, name, bases, attrs): | |
cls.species += 1 | |
print('First, metaclass.__new__ received (metaclass, name, bases, attrs)') | |
print(cls, name, bases, attrs) | |
return super(AnimalMeta, cls).__new__(cls, name, bases, attrs) | |
def __init__(self, name, bases, attrs): | |
print('Second, metaclass.__init__ received (self, name, bases, attrs)') | |
print(self, name, bases, attrs) | |
#def __call__(self, *args, **kwargs): | |
# pass | |
class Cat(with_meta(AnimalMeta)): | |
name = 'cat' | |
def __init__(self): | |
print('Meow') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment