SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler offline
stupid
stupid awesome
stupid awesome python
stupid awesome python tricks
stupid awesome python tricks stupid
stupid awesome python tricks stupid awesome
stupid awesome python tricks stupid awesome python
stupid awesome python tricks stupid awesome python tricks
stupid awesome python tricks stupid awesome python bryan helmig
# python has... oddities
import sys
print >>sys.stdout, 'hello world!'
# hello world!
from __builtin__ import int
# ... uh thanks?
from __builtin__ import True as False
# uh oh...
from __future__ import braces
# ... SyntaxError: not a chance
likes_art = True
# trivia: what am i?
where_to_go = likes_art and 'museum' or 'nascar'
# this is another way to do it...
where_to_go = ('nascar', 'museum')[bool(likes_art)]
# lazily now!
where_to_go = (lambda: 'nascar', lambda: 'museum')[bool(likes_art)]()
# greanevrf - gunax tbq sbe clguba >2.5!
# jure_g_tb = 'zhfrhz' vs yvxrf_neg ryfr 'anfpne'
likes_art = True
# trivia: what am i?
where_to_go = likes_art and 'museum' or 'nascar'
# this is another way to do it...
where_to_go = ('nascar', 'museum')[bool(likes_art)]
# lazily now!
where_to_go = (lambda: 'nascar', lambda: 'museum')[bool(likes_art)]()
# ternaries - thank god for python >2.5!
where_to_go = 'museum' if likes_art else 'nascar'
# str encoding
print 'hello world!'.encode('rot13')
# uryyb jbeyq!
print 'hello world!'.encode('rot13').decode('rot13')
# hello world!
print 'hello world!.'.encode('zlib')
# xx9cxcbHxcdxc9xc9W(xcf/xcaIQT(xc9xc8...
print 'hello world!'.encode('zlib').decode('zlib')
# hello world!
# registering custom str encoding
def register_codec(name, encode=None, decode=None):
import codecs
if not encode:
def encode(val):
raise Exception(name + ' does not support encoding')
if not decode:
def decode(val):
raise Exception(name + ' does not support decoding')
def codec(searched_name):
if searched_name != name:
return None
return codecs.CodecInfo(
name=name, encode=encode, decode=decode)
codecs.register(codec)
# custom "reverser" encoding
def reverser(val):
return val[::-1], len(val)
register_codec('reverser', encode=reverser, decode=reverser)
print 'hello world!'.encode('reverser')
# !dlrow olleh
print 'hello world!'.encode('reverser').decode('reverser')
# hello world!
# custom "hail mary" decoder
def hail_mary_decode(val):
import chardet
result = chardet.detect(val)
return val.decode(result['encoding']), len(val)
register_codec('hail_mary', decode=hail_mary_decode)
print 'xe3x82xabxe3x83xacxe3x83xb3xe3x83x80'.decode('utf-8')
#
print 'xe3x82xabxe3x83xacxe3x83xb3xe3x83x80'.decode('hail_mary')
#
print 'xa5xabxa5xecxa5xf3xa5xc0'.decode('euc_jp')
#
print 'xa5xabxa5xecxa5xf3xa5xc0'.decode('hail_mary')
#
# slicing / indexing / keying
print range(10)[0]
# 0
print range(10)[0:5]
# [0, 1, 2, 3, 4]
print range(10)[::2]
# [0, 2, 4, 6, 8]
print range(10)[::-1]
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print dict(hello='world')['hello']
# world
# deep slicing / indexing / keying
class PassThrough(object):
def __getitem__(self, name):
# magic method to return syntax args directly
return name
pass_through = PassThrough()
print pass_through[1]
# 1
print pass_through[1, 2, 3]
# (1, 2, 3)
print pass_through['hello world!']
# hello world!
# slicing gets weird
print pass_through[:]
# slice(None, None, None)
print pass_through[...]
# Ellipsis
print pass_through[..., ..., ..., ...]
# (Ellipsis, Ellipsis, Ellipsis, Ellipsis)
print pass_through[..., :, ...]
# (Ellipsis, slice(None, None, None), Ellipsis)
# abusing slicing
class parens_be_gone(object):
# square brackets are better than parens
def __init__(self, func):
self.func = func
def __getitem__(self, args):
if not isinstance(args, tuple):
args = (args,)
return self.func(*args)
def __call__(self, *a, **kw):
raise Exception('We do not like (), try []?')
# activate slice abuse
@parens_be_gone
def sum_nums(*args):
return sum(args)
@parens_be_gone
def shout_it(name):
return 'HELLO {}!'.format(name.upper())
print sum_nums[1, 2, 3, 4, 5]
# 15
print shout_it['bryan']
# HELLO WORLD!
# magic methods
class Roughly(object):
def __init__(self, num):
self.num = num
def __invert__(self):
return '%d ± 10%' % self.num
print ~Roughly(5)
# 5 ± 10%
# magic methods continued
class DoublePlus(object):
def __init__(self, plusses=0):
self.plusses = plusses
def __pos__(self):
return DoublePlus(self.plusses + 1)
def __repr__(self):
return '%d plusses' % self.plusses
print ++DoublePlus()
# 2 plusses
# complementary magic methods for operators
class Man(object):
def __add__(self, right_other):
if right_other == 'Dog':
return 'best buds'
return self
def __radd__(self, left_other):
if left_other == 'Dog':
return 'bestest buds'
return self
print Man() + 'Dog'
# best buds
print 'Dog' + Man()
# bestest buds
# magic methods to act like you aren't using python
class pipe(object):
def __init__(self, func):
self.func = func
def __ror__(self, other):
return self.func(other)
def __call__(self, *a, **kw):
return pipe(lambda x: self.func(x, *a, **kw))
# magic methods to act like you aren't using python continued
@pipe
def _map(iterable, func):
return [func(i) for i in iterable]
@pipe
def _filter(iterable, func):
return [i for i in iterable if func(i)]
print (range(10)
| _map(lambda i: i * 3)
| _filter(lambda i: i % 2 == 0)
| _map(str))
# ['0', '6', '12', '18', '24']
# magic methods for elegant DSLs
class RegexEquals(object):
def __init__(self, regex):
import re
self.regex = re.compile(regex)
def __eq__(self, other):
return bool(self.regex.match(other))
class TypeEquals(object):
def __init__(self, *tipes):
self.tipes = tipes
def __eq__(self, other):
return isinstance(other, self.tipes)
# magic methods for elegant DSLs continued
URL = RegexEquals(r'(https?|ftp)://[^s/$.?#].[^s]*')
NUM = RegexEquals(r'd+')
INT = TypeEquals(int, long)
print 'larry' == URL
# False
print 'http://zapier.com/' == URL
# True
print '123' == NUM
# True
print {'url': 'http://zapier.com/', 'visits': 4} == {'url': URL, 'visits': INT}
# True
# magic methods for abuse
class DidYouMean(object):
def __getattr__(self, name):
if name.startswith('__'):
raise AttributeError('No magic did you mean.')
from difflib import SequenceMatcher
scored_attrs = [
(SequenceMatcher(None, name, attr).ratio(), attr)
for attr in dir(self) if not attr.startswith('__')
]
sorted_attrs = sorted([
(score, attr) for score, attr in scored_attrs if score > 0.5
], reverse=True)
best_name = next(iter(sorted_attrs), (None, None))[1]
if not best_name:
raise AttributeError('No "matching" `%s` attribute' % name)
return getattr(self, best_name)
# activate magic methods abuse
class SomeModel(DidYouMean):
first_name = 'bryan'
last_name = 'helmig'
person = SomeModel()
print person.first_name
# bryan
print person.furst_name
# bryan
print person.address
# .. AttributeError: No "matching" `address` attribute
# magic methods for evil
class specialint(int):
def __add__(self, right_other):
if self == 1 and right_other == 1:
return 3
return super(specialint, self).__add__(right_other)
print specialint(1) + 1
# 3
__builtins__.int = specialint
print int(1) + 1
# 3
print 1 + 1
# 2
# literals get coerced way before builtins are referenced... ¯_( )_/¯
# https://benkurtovic.com/2015/01/28/python-object-replacement.html
# http://blaag.haard.se/Using-the-AST-to-hack-constants-into-Python/
# ast / parser
import parser
tree = parser.expr('(a + 1) or {1: "test"}').tolist()
print tree
# [258, [327, [312, [313, [314, [315, [316, [317, [318, [7, '('] ..
# [ ... [3, '"test"'], [27, '}']], [4, ''], ...]
def recurse(val):
import token
if isinstance(val, int):
return token.tok_name.get(val, val)
elif isinstance(val, list):
return [recurse(v) for v in val]
return val
print recurse(tree)
# [258, [327, [312, [313, [314, [315, [316, [317, [318, [7, '('] ..
# [ ... ['STRING', '"test"'], ['RBRACE', '}']], ['NEWLINE', ''], ...]
# ast tools can be repurposed and practical
def pyson(val):
# JSON is lame. Eval is lame.
import ast
return ast.literal_eval(val)
print pyson('"hello world!"')
# hello world!
print pyson("{1234: 'integer keys!'}")
# {1234: 'integer keys!''}
print pyson('import json')
# ... SyntaxError: invalid syntax
# mini lisp calc
def tokenize(program):
return program.replace('(', ' ( ').replace(')', ' ) ').split()
def reshape_tokens(tokens):
token = tokens.pop(0)
if '(' == token:
deep_tokens = []
while tokens[0] != ')':
deep_tokens.append(reshape_tokens(tokens))
tokens.pop(0)
return deep_tokens
try: return int(token)
except: return token
program = '(* 2 (+ 3 5))'
print tokenize(program)
# ['(', '*', '2', '(', '+', '3', '5', ')', ')']
print reshape_tokens(tokenize(program))
# ['*', 2, ['+', 3, 5]]
# mini lisp calc continued
import operator
global_env = {'+': operator.add, '-': operator.sub,
'*': operator.mul, '/': operator.div}
def evaluate(tokens, env=global_env.copy()):
if isinstance(tokens, basestring) and tokens in env:
return env[tokens]
elif not isinstance(tokens, list):
return tokens
else:
func = evaluate(tokens[0], env)
args = [evaluate(arg, env) for arg in tokens[1:]]
return func(*args)
program = '(* 2 (+ 3 5))'
print evaluate(read_tokens(tokenize(program)))
# 16
# http://norvig.com/lispy.html & http://norvig.com/lispy2.html

Mais conteúdo relacionado

Mais procurados

Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
vidyamittal
 
C++totural file
C++totural fileC++totural file
C++totural file
halaisumit
 

Mais procurados (20)

Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
ES6 - Level up your JavaScript Skills
ES6 - Level up your JavaScript SkillsES6 - Level up your JavaScript Skills
ES6 - Level up your JavaScript Skills
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxygine
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Arduino coding class
Arduino coding classArduino coding class
Arduino coding class
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 

Destaque

2005 Cuban Tourism Presentation "Making up for lost time"
2005 Cuban Tourism Presentation "Making up for lost time"2005 Cuban Tourism Presentation "Making up for lost time"
2005 Cuban Tourism Presentation "Making up for lost time"
Ally Stoltz
 
PNG : A Million Different Journeys
PNG : A Million Different JourneysPNG : A Million Different Journeys
PNG : A Million Different Journeys
Ally Stoltz
 
Paratirisymperasmata
ParatirisymperasmataParatirisymperasmata
Paratirisymperasmata
demikok
 
Payforit4 training jul13
Payforit4 training jul13Payforit4 training jul13
Payforit4 training jul13
ImpulsePay
 
Lets get rocked
Lets get rockedLets get rocked
Lets get rocked
djcspartan
 
Alimentos elaborados
Alimentos elaboradosAlimentos elaborados
Alimentos elaborados
hunain25
 
Alcohol and other drugs procedure[1]
Alcohol and other drugs procedure[1]Alcohol and other drugs procedure[1]
Alcohol and other drugs procedure[1]
Spade Aspade
 
エンディングノートとは?
エンディングノートとは?エンディングノートとは?
エンディングノートとは?
a.terada
 
Edlt116 learners and teaching assignment 2 e portfolio
Edlt116 learners and teaching assignment 2 e portfolioEdlt116 learners and teaching assignment 2 e portfolio
Edlt116 learners and teaching assignment 2 e portfolio
jpapps
 
Edss223 assignment 2
Edss223 assignment 2Edss223 assignment 2
Edss223 assignment 2
jpapps
 
Engl001 assignment 1
Engl001 assignment 1Engl001 assignment 1
Engl001 assignment 1
jpapps
 
Lets get rocked
Lets get rockedLets get rocked
Lets get rocked
djcspartan
 
Δραστηριότητες
ΔραστηριότητεςΔραστηριότητες
Δραστηριότητες
demikok
 

Destaque (20)

Ag pres sopac_contestability_public_sector_business_model_of_the_future_march...
Ag pres sopac_contestability_public_sector_business_model_of_the_future_march...Ag pres sopac_contestability_public_sector_business_model_of_the_future_march...
Ag pres sopac_contestability_public_sector_business_model_of_the_future_march...
 
Raa taltree presentation
Raa taltree presentationRaa taltree presentation
Raa taltree presentation
 
2005 Cuban Tourism Presentation "Making up for lost time"
2005 Cuban Tourism Presentation "Making up for lost time"2005 Cuban Tourism Presentation "Making up for lost time"
2005 Cuban Tourism Presentation "Making up for lost time"
 
Kateeeeeeeeeeeeeeeeeeeee
KateeeeeeeeeeeeeeeeeeeeeKateeeeeeeeeeeeeeeeeeeee
Kateeeeeeeeeeeeeeeeeeeee
 
PNG : A Million Different Journeys
PNG : A Million Different JourneysPNG : A Million Different Journeys
PNG : A Million Different Journeys
 
Paratirisymperasmata
ParatirisymperasmataParatirisymperasmata
Paratirisymperasmata
 
Ag pres cpa public_sector leaders_series_luncheon_june_27_2014
Ag pres cpa public_sector leaders_series_luncheon_june_27_2014Ag pres cpa public_sector leaders_series_luncheon_june_27_2014
Ag pres cpa public_sector leaders_series_luncheon_june_27_2014
 
FMSEA 2012 generic slides
FMSEA 2012 generic slidesFMSEA 2012 generic slides
FMSEA 2012 generic slides
 
Payforit4 training jul13
Payforit4 training jul13Payforit4 training jul13
Payforit4 training jul13
 
Lets get rocked
Lets get rockedLets get rocked
Lets get rocked
 
Alimentos elaborados
Alimentos elaboradosAlimentos elaborados
Alimentos elaborados
 
Alcohol and other drugs procedure[1]
Alcohol and other drugs procedure[1]Alcohol and other drugs procedure[1]
Alcohol and other drugs procedure[1]
 
エンディングノートとは?
エンディングノートとは?エンディングノートとは?
エンディングノートとは?
 
Edlt116 learners and teaching assignment 2 e portfolio
Edlt116 learners and teaching assignment 2 e portfolioEdlt116 learners and teaching assignment 2 e portfolio
Edlt116 learners and teaching assignment 2 e portfolio
 
Edss223 assignment 2
Edss223 assignment 2Edss223 assignment 2
Edss223 assignment 2
 
Engl001 assignment 1
Engl001 assignment 1Engl001 assignment 1
Engl001 assignment 1
 
Dust bowl
Dust bowlDust bowl
Dust bowl
 
Dust bowl
Dust bowlDust bowl
Dust bowl
 
Lets get rocked
Lets get rockedLets get rocked
Lets get rocked
 
Δραστηριότητες
ΔραστηριότητεςΔραστηριότητες
Δραστηριότητες
 

Semelhante a Stupid Awesome Python Tricks

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
chrismdp
 

Semelhante a Stupid Awesome Python Tricks (20)

A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
Javascript
JavascriptJavascript
Javascript
 
Beware sharp tools
Beware sharp toolsBeware sharp tools
Beware sharp tools
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 
Node.js API pitfalls
Node.js API pitfallsNode.js API pitfalls
Node.js API pitfalls
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Beyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeBeyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCode
 

Último

Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 

Stupid Awesome Python Tricks

  • 1. stupid stupid awesome stupid awesome python stupid awesome python tricks stupid awesome python tricks stupid stupid awesome python tricks stupid awesome stupid awesome python tricks stupid awesome python stupid awesome python tricks stupid awesome python tricks stupid awesome python tricks stupid awesome python bryan helmig
  • 2. # python has... oddities import sys print >>sys.stdout, 'hello world!' # hello world! from __builtin__ import int # ... uh thanks? from __builtin__ import True as False # uh oh... from __future__ import braces # ... SyntaxError: not a chance
  • 3. likes_art = True # trivia: what am i? where_to_go = likes_art and 'museum' or 'nascar' # this is another way to do it... where_to_go = ('nascar', 'museum')[bool(likes_art)] # lazily now! where_to_go = (lambda: 'nascar', lambda: 'museum')[bool(likes_art)]() # greanevrf - gunax tbq sbe clguba >2.5! # jure_g_tb = 'zhfrhz' vs yvxrf_neg ryfr 'anfpne'
  • 4. likes_art = True # trivia: what am i? where_to_go = likes_art and 'museum' or 'nascar' # this is another way to do it... where_to_go = ('nascar', 'museum')[bool(likes_art)] # lazily now! where_to_go = (lambda: 'nascar', lambda: 'museum')[bool(likes_art)]() # ternaries - thank god for python >2.5! where_to_go = 'museum' if likes_art else 'nascar'
  • 5. # str encoding print 'hello world!'.encode('rot13') # uryyb jbeyq! print 'hello world!'.encode('rot13').decode('rot13') # hello world! print 'hello world!.'.encode('zlib') # xx9cxcbHxcdxc9xc9W(xcf/xcaIQT(xc9xc8... print 'hello world!'.encode('zlib').decode('zlib') # hello world!
  • 6. # registering custom str encoding def register_codec(name, encode=None, decode=None): import codecs if not encode: def encode(val): raise Exception(name + ' does not support encoding') if not decode: def decode(val): raise Exception(name + ' does not support decoding') def codec(searched_name): if searched_name != name: return None return codecs.CodecInfo( name=name, encode=encode, decode=decode) codecs.register(codec)
  • 7. # custom "reverser" encoding def reverser(val): return val[::-1], len(val) register_codec('reverser', encode=reverser, decode=reverser) print 'hello world!'.encode('reverser') # !dlrow olleh print 'hello world!'.encode('reverser').decode('reverser') # hello world!
  • 8. # custom "hail mary" decoder def hail_mary_decode(val): import chardet result = chardet.detect(val) return val.decode(result['encoding']), len(val) register_codec('hail_mary', decode=hail_mary_decode) print 'xe3x82xabxe3x83xacxe3x83xb3xe3x83x80'.decode('utf-8') # print 'xe3x82xabxe3x83xacxe3x83xb3xe3x83x80'.decode('hail_mary') # print 'xa5xabxa5xecxa5xf3xa5xc0'.decode('euc_jp') # print 'xa5xabxa5xecxa5xf3xa5xc0'.decode('hail_mary') #
  • 9. # slicing / indexing / keying print range(10)[0] # 0 print range(10)[0:5] # [0, 1, 2, 3, 4] print range(10)[::2] # [0, 2, 4, 6, 8] print range(10)[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] print dict(hello='world')['hello'] # world
  • 10. # deep slicing / indexing / keying class PassThrough(object): def __getitem__(self, name): # magic method to return syntax args directly return name pass_through = PassThrough() print pass_through[1] # 1 print pass_through[1, 2, 3] # (1, 2, 3) print pass_through['hello world!'] # hello world!
  • 11. # slicing gets weird print pass_through[:] # slice(None, None, None) print pass_through[...] # Ellipsis print pass_through[..., ..., ..., ...] # (Ellipsis, Ellipsis, Ellipsis, Ellipsis) print pass_through[..., :, ...] # (Ellipsis, slice(None, None, None), Ellipsis)
  • 12. # abusing slicing class parens_be_gone(object): # square brackets are better than parens def __init__(self, func): self.func = func def __getitem__(self, args): if not isinstance(args, tuple): args = (args,) return self.func(*args) def __call__(self, *a, **kw): raise Exception('We do not like (), try []?')
  • 13. # activate slice abuse @parens_be_gone def sum_nums(*args): return sum(args) @parens_be_gone def shout_it(name): return 'HELLO {}!'.format(name.upper()) print sum_nums[1, 2, 3, 4, 5] # 15 print shout_it['bryan'] # HELLO WORLD!
  • 14. # magic methods class Roughly(object): def __init__(self, num): self.num = num def __invert__(self): return '%d ± 10%' % self.num print ~Roughly(5) # 5 ± 10%
  • 15. # magic methods continued class DoublePlus(object): def __init__(self, plusses=0): self.plusses = plusses def __pos__(self): return DoublePlus(self.plusses + 1) def __repr__(self): return '%d plusses' % self.plusses print ++DoublePlus() # 2 plusses
  • 16. # complementary magic methods for operators class Man(object): def __add__(self, right_other): if right_other == 'Dog': return 'best buds' return self def __radd__(self, left_other): if left_other == 'Dog': return 'bestest buds' return self print Man() + 'Dog' # best buds print 'Dog' + Man() # bestest buds
  • 17. # magic methods to act like you aren't using python class pipe(object): def __init__(self, func): self.func = func def __ror__(self, other): return self.func(other) def __call__(self, *a, **kw): return pipe(lambda x: self.func(x, *a, **kw))
  • 18. # magic methods to act like you aren't using python continued @pipe def _map(iterable, func): return [func(i) for i in iterable] @pipe def _filter(iterable, func): return [i for i in iterable if func(i)] print (range(10) | _map(lambda i: i * 3) | _filter(lambda i: i % 2 == 0) | _map(str)) # ['0', '6', '12', '18', '24']
  • 19. # magic methods for elegant DSLs class RegexEquals(object): def __init__(self, regex): import re self.regex = re.compile(regex) def __eq__(self, other): return bool(self.regex.match(other)) class TypeEquals(object): def __init__(self, *tipes): self.tipes = tipes def __eq__(self, other): return isinstance(other, self.tipes)
  • 20. # magic methods for elegant DSLs continued URL = RegexEquals(r'(https?|ftp)://[^s/$.?#].[^s]*') NUM = RegexEquals(r'd+') INT = TypeEquals(int, long) print 'larry' == URL # False print 'http://zapier.com/' == URL # True print '123' == NUM # True print {'url': 'http://zapier.com/', 'visits': 4} == {'url': URL, 'visits': INT} # True
  • 21. # magic methods for abuse class DidYouMean(object): def __getattr__(self, name): if name.startswith('__'): raise AttributeError('No magic did you mean.') from difflib import SequenceMatcher scored_attrs = [ (SequenceMatcher(None, name, attr).ratio(), attr) for attr in dir(self) if not attr.startswith('__') ] sorted_attrs = sorted([ (score, attr) for score, attr in scored_attrs if score > 0.5 ], reverse=True) best_name = next(iter(sorted_attrs), (None, None))[1] if not best_name: raise AttributeError('No "matching" `%s` attribute' % name) return getattr(self, best_name)
  • 22. # activate magic methods abuse class SomeModel(DidYouMean): first_name = 'bryan' last_name = 'helmig' person = SomeModel() print person.first_name # bryan print person.furst_name # bryan print person.address # .. AttributeError: No "matching" `address` attribute
  • 23. # magic methods for evil class specialint(int): def __add__(self, right_other): if self == 1 and right_other == 1: return 3 return super(specialint, self).__add__(right_other) print specialint(1) + 1 # 3 __builtins__.int = specialint print int(1) + 1 # 3 print 1 + 1 # 2 # literals get coerced way before builtins are referenced... ¯_( )_/¯ # https://benkurtovic.com/2015/01/28/python-object-replacement.html # http://blaag.haard.se/Using-the-AST-to-hack-constants-into-Python/
  • 24. # ast / parser import parser tree = parser.expr('(a + 1) or {1: "test"}').tolist() print tree # [258, [327, [312, [313, [314, [315, [316, [317, [318, [7, '('] .. # [ ... [3, '"test"'], [27, '}']], [4, ''], ...] def recurse(val): import token if isinstance(val, int): return token.tok_name.get(val, val) elif isinstance(val, list): return [recurse(v) for v in val] return val print recurse(tree) # [258, [327, [312, [313, [314, [315, [316, [317, [318, [7, '('] .. # [ ... ['STRING', '"test"'], ['RBRACE', '}']], ['NEWLINE', ''], ...]
  • 25. # ast tools can be repurposed and practical def pyson(val): # JSON is lame. Eval is lame. import ast return ast.literal_eval(val) print pyson('"hello world!"') # hello world! print pyson("{1234: 'integer keys!'}") # {1234: 'integer keys!''} print pyson('import json') # ... SyntaxError: invalid syntax
  • 26. # mini lisp calc def tokenize(program): return program.replace('(', ' ( ').replace(')', ' ) ').split() def reshape_tokens(tokens): token = tokens.pop(0) if '(' == token: deep_tokens = [] while tokens[0] != ')': deep_tokens.append(reshape_tokens(tokens)) tokens.pop(0) return deep_tokens try: return int(token) except: return token program = '(* 2 (+ 3 5))' print tokenize(program) # ['(', '*', '2', '(', '+', '3', '5', ')', ')'] print reshape_tokens(tokenize(program)) # ['*', 2, ['+', 3, 5]]
  • 27. # mini lisp calc continued import operator global_env = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div} def evaluate(tokens, env=global_env.copy()): if isinstance(tokens, basestring) and tokens in env: return env[tokens] elif not isinstance(tokens, list): return tokens else: func = evaluate(tokens[0], env) args = [evaluate(arg, env) for arg in tokens[1:]] return func(*args) program = '(* 2 (+ 3 5))' print evaluate(read_tokens(tokenize(program))) # 16 # http://norvig.com/lispy.html & http://norvig.com/lispy2.html