31
COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) COMP10001 Foundations of Computing PEP8, Modules and Files Semester 1, 2017 Tim Baldwin & Egemen Tanin version: 1102, date: March 29, 2017 © 2017 The University of Melbourne

COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

COMP10001 Foundations of Computing

PEP8, Modules and Files

Semester 1, 2017Tim Baldwin & Egemen Tanin

— version: 1102, date: March 29, 2017 —

© 2017 The University of Melbourne

Page 2: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Reminders

• Grok Worksheets 8–11 due at the end of thisweek

• Have a go at the early-release tutesheet (see the“Lectures/Workshops” page on the LMS) priorto your workshop this week

• Project 1 due at the end of Friday of next week

Page 3: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Lecture Agenda

• Last lecture:• More detail on functions and mutability

• This lecture:• Functions and namespaces• PEP8• Modules• File access

Page 4: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Lecture Outline

1 Functions and Namespaces

2 PEP8

3 Modules

4 Files

Page 5: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Namespaces I

• A “namespace” is a mapping (dictionary!) fromnames to objects (eg variables and functions).

• When Python starts up there is the globalnamespace

• When a function is called, a local namespace forthat function is called, and then forgotten whenthe function ends

• Scope is the area of Python code where aparticular namespace is used

Page 6: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Namespaces II1 a = 3

2 def f(x):

3 i = 2

4 return x+i

5 b = 6

In this code snippet

• The global namespace contains a, f and b

• When f is called, its local namespace has x and i

When Python tries to find an object, it first looks inthe local namespace, and then in the globalnamespace

Page 7: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Namespaces III1 i = 3

2 def f(x):

3 i = 1

4 return x+i

5 print(f(10))

• In this case, the Line 4 code uses the i in itslocal namespace (Line 3)

• Scope of x is Lines 2,3,4.

• Scope of global i is Lines 1, 2 and 5.

• Scope of the i in f is Lines 3 and 4.

Page 8: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Namespaces IVNow for the tricky part: functions within functions

1 i = 3

2 def f(x):

3 i = 2

4

5 def g(x):

6 i = 1

7 return x+i

8

9 return g(x+i)

10

11 print(f(10))

12 print(g(10))

f’s namespace contains g and others

Page 9: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Namespaces V

1 def f(x):

2 i = 1

3

4 def g(x):

5 return(x+i)

6

7 return(g(x+i))

8

9 print(f(10))

Python searches local namespace, and then enclosingfunction namespaces, and then global namespace.You can list the current namespace with dir().

Page 10: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Make life easy

• Don’t use the same parameter names insub-functions

• Avoid global variables wherever possible (always!)

• Capitalize constants (a common convention)

def f(x):

ADDER_F = 2

def g(y):

ADDER_G = 1

return(y + ADDER_G)

return(g(x + ADDER_F ))

Page 11: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Lecture Outline

1 Functions and Namespaces

2 PEP8

3 Modules

4 Files

Page 12: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic

• As you are perhaps picking up on gradually,Python is big on stylistics and readability, and theidea that there is one “right” way of doing things

• In this vein, Python has stylistic guidelines on“right” and “wrong” ways of writing code (=PEP8), some of which we take on board in thissubject, and start automatically checking for inyour code from Worksheet 10 (and for all theprojects)

Page 13: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: White Space

• Indentation should always be in multiples of 4spaces (which Grok does by default; so long asyou don’t modify this/code outside Grok, youshould be fine):

• There should be a single space between operatorsand their operands, and after commas:

7 Wrong:w_len=0

for i in ('a','b'):w_len=w_len +1

3 Right:w_len = 0

for i in ('a', 'b'):w_len = w_len + 1

Page 14: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Avoid Long Lines

• Lines must not exceed 79 characters

7 Wrong:def fun(thing):

'''take `thing ` and do nothing to it , but document it in a long -winded way '''if 0 > 1 and "totoro" in "avengers" and "abracadabra".isalpha ():

pass

return thing

3 Right:def fun(thing):

'''take `thing ` and do nothing to it , but

document it in a long -winded way '''if 0 > 1 and "totoro" in "avengers" and \

"abracadabra".isalpha ():

pass

return thing

Page 15: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Segmentation

• Use blank lines to separate logical sections:

7 Wrong:def w_count(word):

w_len = 0

for char in word:

w_len += 1

return w_len

3 Right:def w_count(word):

# letter count

w_len = 0

# count the letters

for char in word:

w_len += 1

return w_len

Page 16: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Don’t Stack

• Avoid multiple statements on the same line

• Always start a new line after if, elif, else,while, for, etc.

7 Wrong:a = True; b = 0

if a: b += 1

else: b += 2

3 Right:a = True

b = 0

if a:

b += 1

else:

b += 2

Page 17: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Comment Sensibly

• Make sure your comments do not contradict yourcode

• Do not state the obvious in comments

7 Wrong:# initialise `a` to 0

a = 0

# increment `a`a -= 1

3 Right:# count of letters

a = 0

a -= 1

Page 18: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Name Sensibly

• Never use the characters l, O or I assingle-character variable names

• Use self-descriptive variable names

7 Wrong:l = I = 1

O = 0

3 Right:count = min_val = 1

max_val = 0

Page 19: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Function Names

• Function names should be lowercase, with wordsseparated by underscores as necessary to improvereadability

7 Wrong:def DOSOMETHING(x):

...

3 Right:def do_something(x):

...

Page 20: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Constant Names

• Constants should be written in all capital letterswith underscores separating words, and listed inthe “header” of your code

7 Wrong:k = 3

def fun(i, k=k):

....

3 Right:CHAR_SIZE = 3

def fun(i, k=CHAR_SIZE ):

....

Page 21: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Going Pythonic: Comparing Booleans

• Don’t compare Boolean values to True or False

using ==

7 Wrong:if val == False:

....

elif val == True:

....

if val2 == True:

return True

else:

return False

3 Right:if not val:

....

else:

....

return val2

Page 22: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Lecture Outline

1 Functions and Namespaces

2 PEP8

3 Modules

4 Files

Page 23: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Modules I

• Modules are pre-prepared “stores” of convenientmethods/variables which expand the functionalityof Python

• To access the contents of a module, import it

import math

area = math.pi * radius **2

phi = (1 + math.sqrt (5))/2

• import adds the module to the local namespace

Page 24: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Modules II1 def area(radius ):

2 import math

3 return math.pi * radius **2

4

5 print(area (2))

6 print(pi)

• What is in the local namespace of area?

• What is in the global namespace?

• Does line 6 work?

Page 25: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Modules III• It is also possible (but generally avoided) to

import all methods and constants from a libraryinto the local namespace:

from math import *

area = pi * radius **2

• Alternatively you can selectively import objects:

from math import pi, e

area = pi * radius **2

including the possibility of renaming them:

from math import pi as mypi

area = mypi * radius **2

Page 26: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Lecture Outline

1 Functions and Namespaces

2 PEP8

3 Modules

4 Files

Page 27: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Files

• Computer memory is volatile• RAM, cache, registers• Power off, it is all gone• Python program finishes, it is all gone

• Computers use “disk” for longer term storage• A physical hard disk that mechanically spins• Flash drives without mechanical parts• “The cloud” (sends it off to a physical disk)

• Disks have “filesystems” (except on systems suchas iOS, where data is linked to an app)

• Python can read and write files

Page 28: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Reading Files

• Reading data in from a (local) file:

FILENAME = 'jabberwocky.txt'text = open(FILENAME ).read()

lines = open(FILENAME ). readlines ()

fp = open(FILENAME)

for line in fp:

...

• read() reads the entire file

• readlines() reads into a list of lines

• for iterates over lines in the file

Page 29: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

File Writing/Appending

• Writing to a file:

FILENAME = 'file.txt'text = open(FILENAME ,'w')text.write('Tim woz ere')text.close()

• Appending to a file:

FILENAME = 'file.txt'text = open(FILENAME ,'a')text.write('Tim woz ere again ')text.close()

Page 30: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

File Generators

• Even better, you can use a “generator”:

with open('file.txt') as f:

for line in f:

print(line)

with the advantage that:• it automatically closes the file• it is more efficient than direct iteration

Page 31: COMP10001 Foundations of Computing PEP8, Modules and Files · 2017. 4. 21. · COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017) Going Pythonic • As you are perhaps

COMP10001 Foundations of Computing Week 5, Lecture 1 (27/3/2017)

Lecture Summary

• What is PEP8, and what are stylistic conventionsto look out for in Python?

• What are modules?

• How do you read a file?

• What is defaultdict and why is it useful?

• What are list comprehensions and why are theyuseful?

• What do += and *= mean?