Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python for the Ruby Programmer

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
Tweet

More Decks by Brian Riley

Other Decks in Programming

Transcript

  1. BRIAN WHO? •Freelance programmer •Worked on many Python projects and

    at startups •I actually like Rubby •Once had a run in with the yakuza
  2. BUT NOT ALWAYS puts "Hello, world!" hello_world.py hello_world.rb def greet():

    print "Hello, world!" if __name__ == '__main__': greet()
  3. ENVIRONMENT $ python >>> print "Hello, world!" Hello, world! >>>

    exit() $ irb > puts "Hello, world!" Hello, world! => nil > exit
  4. 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!
  5. 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!
  6. 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()
  7. 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()
  8. 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'
  9. 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!"} )
  10. 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!
  11. FUNCTION() VS FUNCTION >>> def hello_world(): ... print "Hello, world!"

    ... >>> hello_world() Hello, world! >>> hello_world <function hello_world at 0x106aca050> >>>
  12. 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]()
  13. LIST COMPREHENSIONS cool_kids = [] for user in users: if

    user.does_program_ruby(): cool_kids.append(user)
  14. LIST COMPREHENSIONS cool_kids = [] for user in users: if

    user.does_program_ruby(): cool_kids.append(user)
  15. 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]
  16. 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): # ...
  17. CONTEXT MANAGERS f = open('cat.gif', 'r') # ... f.close() #

    same as above with open('cat.gif', 'r') as f: # ...
  18. __METHODS__ class Python(object): def __init__(self, herp, derp): # I'm a

    constructor, duh self.herp = derp self.derp = herp
  19. __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
  20. 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