Skip to content

Instantly share code, notes, and snippets.

@cjlucas
Last active August 29, 2015 14:27
Show Gist options
  • Save cjlucas/6e6b2027d7393687569c to your computer and use it in GitHub Desktop.
Save cjlucas/6e6b2027d7393687569c to your computer and use it in GitHub Desktop.
Quick rundown of python
## The basics
print('Hello world')
## Primatives types
a_string = 'hithere'
a_int = 5
a_float = 5.5
a_list = [1, 2, 3]
a_tuple = tuple(a_list) # tuple is an immutable list
a_dict = {'key': 'value'} # dict is a hash map
a_null = None
## Control flow
if a_string == 'hithere' and a_int == 5:
print('in the if')
else:
print('in the else')
# Iteration
# for (i = 0; i < 5; i++)
for i in range(5):
pass # pass is a no-op (basically a concession for not have curly braces in the language)
# iterating of any iterable (list, tuple, string)
for i in a_list:
print(i)
## List operations
a_list = [0, 1, 2, 3]
# access by index
a_list[0] # 0
a_list[-1] # 3
# list slicing
a_list[:] # [0, 1, 2, 3] (also creates a shallow copy of the list)
a_list[0:2] # [0, 1]
a_list[2:4] # [2, 3]
# dict operations
a_dict = {'key' : 'value'}
# get a value at given key
a_dict['key']
# get value at key, or "default_value" if key is missing
a_dict.get('key', 'default_value')
## Importing modules
# import the entire module, preserving the namespace
import os
# import the entire module without namespace (basically "using namespace")
# also, never do this
from os import *
# import select things from a module
from os import listdir
listdir('.')
# determine if given string is a key in the dict
if 'key' in a_dict:
print('key is available!')
## Defining a function
# args - variable length arguments that are placed into an tuple
# kwargs - variable number of keyword arguments are placed in a dict
#
# baz=1 denotes a parameter with a default value (in this case "1")
def foo(bar, baz=1, *args, **kwargs):
print("in foo()")
print("bar = {0}".format(bar))
print("baz = {0}".format(baz))
print("args = {0}".format(args))
print("kwargs = {0}".format(kwargs))
foo('hello', 5, 1, 2, 3, more=4, keyword_args="5")
# bar = hello
# baz = 5
# args = (1, 2, 3)
# kwargs = {'more': 4, 'keyword_args': '5'}
# Functions are first-class citizens
import time
def function_timer(func):
now = time.time()
func()
print("function took {0} seconds to run".format(time.time() - now))
function_timer(time.time)
# lambda, parameters are left of the colon. Whatever is to the right
# is implicitly returned
func = lambda x: x + 1
func(5) # 6
## Defining a class
class Point(object):
# the constructor
# self is the instance of Point
def __init__(self):
# define local variables
self.x = 1
self.y = 2
# cls is Point
@classmethod
def some_class_method(cls, arg):
print("in class method {0} {1}".format(cls, arg))
@staticmethod
def some_static_method(arg):
print("in static method {0}".format(arg))
# called by print() or str()
def __str__(self):
return "({0}, {1})".format(self.x, self.y)
# creating an instance of a Point
p = Point()
p.x = 5
p.y = 10
print(p) # (5, 10)
Point.some_class_method('an_arg')
Point.some_static_method('another_arg')
# Subclassing
class SuperCoolPoint(Point):
def __init__(self):
# call to Point's constructor
super().__init__()
self.something_cool = 'dunno'
# Function annotations
# note: this does *not* perform actual type checking at runtime (though most
# python linters now support this and will raise warnings if an incorrect type is passed).
# This will be good for traceability of the code for a large project, especially
# during code reviews where the reviewer may not have intimate knowledge of the code
def foo2(x: int, stuff: tuple) -> str:
return "a string"
# Exceptions
try:
raise RuntimeError("something went wrong")
except RuntimeError as e:
print(e)
except:
# catchall
pass
finally:
# do cleanup
pass
# Opening a file
# the with ... as syntax will close fp after block has completed
with open('/dev/urandom', 'rb') as fp:
data = fp.read(10)
print(data)
## JSON
import json
a_list = [0, 1, 2]
a_dict = {'key' : a_list}
# serializing an object
json.dumps(a_dict)
# deserializing
json.loads('{"key": [0, 1, 2]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment