Share
Embed
Python for the Ruby Programmer
Talk I gave at the July 12, 2013 LA Ruby meetup: http://www.meetup.com/laruby/events/125997162/
Brian Riley
July 13, 2013
Transcript
25 slides
-
BRIAN WHO? •Freelance programmer •Worked on many Python projects and
at startups •I actually like Rubby •Once had a run in with the yakuza -
ASSUMPTIONS •You’re a Ruby programmer •You can read Python •You
may or may not have worked in Python -
BUT NOT ALWAYS puts "Hello, world!" hello_world.py hello_world.rb def greet():
print "Hello, world!" if __name__ == '__main__': greet() -
ENVIRONMENT $ python >>> print "Hello, world!" Hello, world! >>>
exit() $ irb > puts "Hello, world!" Hello, world! => nil > exit -
ZEN OF PYTHON >>> import this The Zen of Python,
by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! -
ZEN OF PYTHON >>> import this The Zen of Python,
by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! -
BIFS __import__() abs() all() any() apply() basestring() bin() bool() buffer()
bytearray() callable() chr() classmethod() cmp() coerce() compile() complex() delattr() dict() dir() divmod() enumerate() eval() execfile() file() filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() input() int() intern() isinstance() issubclass() iter() len() list() locals() long() map() max() memoryview() min() next() object() oct() open() ord() pow() print() property() range() raw_input() reduce() reload() repr() reversed() round() set() setattr() slice() sorted() staticmethod() str() sum() super() tuple() type() unichr() unicode() vars() xrange() zip() -
BIFS __import__() abs() all() any() apply() basestring() bin() bool() buffer()
bytearray() callable() chr() classmethod() cmp() coerce() compile() complex() delattr() dict() dir() divmod() enumerate() eval() execfile() file() filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() input() int() intern() isinstance() issubclass() iter() len() list() locals() long() map() max() memoryview() min() next() object() oct() open() ord() pow() print() property() range() raw_input() reduce() reload() repr() reversed() round() set() setattr() slice() sorted() staticmethod() str() sum() super() tuple() type() unichr() unicode() vars() xrange() zip() -
LEN() >>> len([1, 2, 3]) 3 >>> [1, 2, 3].length()
Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'length' >>> [1, 2, 3].len() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'len' -
IMPORTS from sys import path import sys sys.path import django
def hello_world(): print django.template.loader.render_to_string( template, {'message': "Hello, world!"} ) -
ZEN OF PYTHON >>> import this The Zen of Python,
by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! -
FUNCTION() VS FUNCTION >>> def hello_world(): ... print "Hello, world!"
... >>> hello_world() Hello, world! >>> hello_world <function hello_world at 0x106aca050> >>> -
FUNCTION() VS FUNCTION import sys def poo(): print u"\U0001F4A9" def
see_no_evil(): print u"\U0001F648" def quit(): sys.exit() def output(input): handlers = { 'poo': poo, 'see no evil': see_no_evil, 'quit': quit } handlers[input]() -
LIST COMPREHENSIONS cool_kids = [] for user in users: if
user.does_program_ruby(): cool_kids.append(user) -
LIST COMPREHENSIONS cool_kids = [] for user in users: if
user.does_program_ruby(): cool_kids.append(user) -
LIST COMPREHENSIONS cool_kids = [user for user in users if
user.does_program_ruby()] import math cubes = [math.pow(3, num) for num in list] -
DICTIONARY COMPREHENSIONS cool_kids = {user.id: user.name for user in users
if user.does_program_ruby()} -
DECORATORS from django.contrib.auth.decorators import login_required def dashboard(request): # ... dashboard
= login_required(dashboard) # the same as above @login_required def dashboard(request): # ... -
CONTEXT MANAGERS f = open('cat.gif', 'r') # ... f.close() #
same as above with open('cat.gif', 'r') as f: # ... -
__METHODS__ class Python(object): def __init__(self, herp, derp): # I'm a
constructor, duh self.herp = derp self.derp = herp -
__METHODS__ >>> class Array(list): ... def __len__(self): ... return 999999999
... >>> array = Array() >>> array.append(1) >>> array.append(2) >>> array.append(3) >>> array [1, 2, 3] >>> len(array) 999999999 Here be dragons -
A STORY OF WHITESPACE >>> def give_me_space_or_give_me_death(): ... print "Death
it is" File "<stdin>", line 2 print "Death it is" ^ IndentationError: expected an indented block