Skip to content

Instantly share code, notes, and snippets.

@ldong
Last active August 29, 2015 14:02
Show Gist options
  • Save ldong/e67d39b1ab4079002808 to your computer and use it in GitHub Desktop.
Save ldong/e67d39b1ab4079002808 to your computer and use it in GitHub Desktop.
Python talk 6/3/2014

Notes

Author: Rick Copland

Date: 6/3/2014

Useful builtins libs

  1. zip enumerate
  2. eval
  3. dir help
  4. chr ord
  5. map filter
  6. sum, max, min & len
  7. repr

zip

enumrate

eval

repr <=> eval

dir

dir(x)

help

help(x)

  1. with docstring

  2. x._doc_

ord

ord('a')

ord(u'你好')

chr(97)

map

map(func, elements)

i.e. map(ord, 'FOO')

filter

filter(func, sequences)

i.e.

def is_even(num): return num % 2 ==0
filter(is_even, xrange(10))

sum, max, min & len

pass

repr

  1. repr, for programmer
  2. str, print
  3. unicode, print

In short, repr is for debugging; str is for uers more

Basic Types

int('5')

int('ff', 16)

float('5')

list([1,2,3])

tuple([1,2,3])

items = [(0, 'a'), (1, 'b')]
dict(items)

keys = range(4)
values['a', 'b', 'c', '4']
dict(zip(keys, values))

dict(foo=1, bar=2, baz=3)

unicode('abcd')

dir(__builtins__)

File I/O

  1. open
  2. sys
  3. os

open

  1. open

    fp = open('/etc/hosts')
    print repr(fp.read(40))
    fp.close()
    
    # does not load the whole file in memory
    for line in fp:
      print repr(line)
    fp.close()
    
    # gives the number of liens
    fp.readlines()
    list(open('/etc/hosts'))
    
    fp.read()
    fp.seek()
    fp.tell()
    
  2. mode

    # r for read
    # w for write
    # a for append
    # w+ for write with reading
    # r+ for reading with writing
    fp = open('/ect/hosts', 'r') 
    
  3. encodings

    1. python2. read with bytestring

    2. python3. read with bytes

Side notes:

  1. Raw String r('h/e/l/l/o/\w\o\r\l\d!')

  2. with open includes automatically close

  3. isinstance(), type()

Python Module

  1. The import statment
  2. sys -- inspect the running process
  3. os -- inspect the operating system
  4. math -- floating point math function
  5. time and datetim
  6. files and the StringIO module

import

alias

  1. import sys as mysys

  2. from sys import path

  3. from sys import path as p

  4. from datetime import datetime, day, time

  5. more

    sys.argv
    sys.executable
    sys.stdin
    sys.stdout
    sys.stderr  # print right way in case sys crushed
    

Side notes:

help(sys.setprofile) -> useful for debuging

sys.maxint

OS

import os
dir(os)

fd.open('ls -l')
print fd.read()

print os.path
dir(os.path)

os.normpath('/usr/local/bin/../../bin')
os.path.expanduser('~')
os.path.expandvars('$HOME is here')

math

import math
help(math)

time (c like)

impor time
time.time()    # epoch time
time.asctime() # readable
time.ctime()   # character time
time.gmtime()  # UTC
time.mktime(time.gmtime())
time.localtime()
time.strftime('2012-11-05', '%Y-%m-%d')
time.strptime('2012-11-05', '%Y-%m-%d')
time.sleep(0.1) # in second time

datetime

import datetime
datetime.datetime.now()
now = datetime.datetime.utcnow()
print repr(now.date())
print repr(now.time())

time.mktime(now.timetuple()) # Epoch

Q & A

  1. Question: help vs dir?

    Answer:

    1. dir gives the attributes
    2. help gives the docstring
  2. Question: repr vs str?

    Answer:

    1. repr for developers
    2. str for users
  3. convert to truthy and falsy

    Answer:

    1. not not
    2. bool()
  4. which is cheaper fp.readlines() or list(open('/etc/hosts'))?

    Answer:

    1. Write your own iterate loop, so it will discard the contents if one don't care.
    2. more
  5. paths

    1. os.env.path(runs in subprocess)
    2. sys.path

References

Python functions

iPython Book

Truthy and Falsy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment