Python (Modern Python 3 Bootcamp, Sections 28-31, Decorators/Testing/FileIO/CSVs/Pickling)

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Since using "w" to write to a file overwrites everything, what flag can be used instead to add to the end of a file?

"a" (append) with open("story.txt", "a") as file: file.write("Adding something to the end!")

Because of the shortcomings of both "w" (write) and "a" (append), the most commonly used mode when needing to read and edit a file is _________.

"r+" Read and write to a file (write based on cursor)

When opening a file that you want to write() to, you must pass what as the second argument?

"w" with open("story.txt", "w") as file: file.write("Writing to files is great.\n")

What flag can be placed in a Python file to ignore all assertions?

-O

What special shorter syntax can you use to signify a decorator?

@

json.dumps formats a Python object as what?

A *string* of JSON

def ______________(fn): def wrapper(*args, **kwargs): # do some stuff with fn(*args, **kwargs) return wrapper This is the standard way that what type of functions are set up? A) Lambdas B) Generators C) Decorators D) None of the above

C

What is a potential drawback of using reader from Python's CSV module? A) It doesn't distinguish a header row by default. B) You have to access individual data by index, rather than name. C) It can only be iterated upon once. D) All of the above.

D

What do we call functions that wrap other functions and enhance their behavior?

Decorators

In FileIO when opening a file, which of the following modes will create a new file if one doesn't exist with the name you call? A) "r" B) "w" C) "a" D) "r+" E) All of the above F) B & C G) B, C & D

F

True or False: Unlike read(), when writing to files you do *not* have to use the open() function.

False

True or False: Unlike reader objects, OrderedDict's can be iterated over more than once.

False

True or False: assert accepts one and only one argument (an expression).

False (It accepts an error message as an optional second argument.)

True or False: Using file.write() tacks on whatever you put to the end of the existing file.

False (It overwrites everything and starts fresh.)

True or False: csv_reader = reader(file) gives you a list object by default.

False But it can be converted to a list easily with something like... data = list(csv_reader)

True or False: assert is a function.

False Even though things like print() and raise() have been changed from statements to functions, assert remains as a *statement*.

self.assertEquals(is_funny("Tim"), False) self.assertFalse(is_funny("Tim")) True or False: There is no difference between these two assertions.

False The first one would be asserting that it *is False*, while the second one would be asserting that it is *falsy*.

True or False: When using a file in "a" (append) mode, you use the file.append() method as well.

False You still use file.write().

A function that either... - returns another function - accepts one or more functions as argument(s) is a what?

Higher Order Function

assert accepts an expression and returns ___________ if that expression is truthy, and raises a(n) _____________ if that expression is falsy.

None AssertionError

What is the name for the special collection in Python of a dictionary where every row has an order?

OrderedDict

When using doctests, you have to write code that looks like it's inside of a __________.

REPL

True or False: The idea of "pickling" is a Python-specific thing.

True

True or False: The seek() method takes in an index -- like any other string has an index -- of where to place the cursor in the file.

True

True or False: Using file.write() with a file that does not exist creates a new file with that name.

True

True or False: Writing when in "r+" mode overwrites the characters from wherever it starts, rather than shifting everything over.

True

True or False: You can use Python's CSV module for data not separated by commas, as long as the data is separated by the same character.

True

What is the command to run doctests on a file?

python3 -m doctest -v file_name.py

When using writer vs DictWriter, there really is no preferred option. writer is usually ___________, while DictWriter is more _____________.

quicker (but less clear) clear (but longer to write)

After using open() to create a file object, you can "read" that file object using the _________ method.

read()

In TDD (Test-Driven Development), development begins by writing __________, and then you write __________ to make those ________ ________.

tests code tests pass

Assert was useful for awhile in Python, but it's been improved upon by a couple other testing methods, most notably __________.

unittest

The most popular and easiest to use method of unit testing in Python is _____________.

unittest

csv_reader = reader(file) __________________________________ for fighter in csv_reader: print(f"{fighter[0]} is from {fighter[1]}" Suppose there is header data that is being included by default in this csv_reader. What could you put in the blank line to alleviate that?

next(csv_reader)

Python3 comes with a built-in _________ function for reading in text files.

open

python3 -O app.py The -O flag when running that file stands for ____________ and will ignore all _______________ in the file.

optimize assertions

Python's built-in json module provides methods to _________ & _________ Python to JSON, and vice versa.

encode & decode

With the CSV module, DictWriter is a bit more complicated than writer because you have to specify ____________.

fieldnames

How do you prevent metadata about function1 being overridden by the wrapper function if function1 has a decorator attached to it?

from functools import wraps def my_decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): """THIS WON'T OVERRIDE ANYMORE""" # whatever logic here @my_decorator def function1(): """THIS WILL CORRECTLY APPEAR""" # whatever logic here

The "magical" part of using DictReader is that the keys for the OrderedDict are automatically set up to be the _________ of the CSV.

headers from csv import DictReader with open("fighters.csv") as file: csv_reader = DictReader(file) for row in csv_reader: # each row is an OrderedDict! print(row['Name'])

One drawback of using reader instead of DictReader is that, when you're iterating over the rows, you have to access individual pieces of that row via _________.

index for fighter in csv_reader: print(f"{fighter[0]} is from {fighter[1]}"

While pickling is nice, there is an outside module called ______________ that allows you to pickle Python to JSON and it also makes the files more readable while they're stored.

jsonpickle

With reader, every row is a(n) _____________. With DictReader, every row is a(n) ____________.

list OrderedDict

def test_midnight_time(self): """Should change 12 to 00 when it's the midnight hour""" self.assertEqual(convert_time_to_military(midnight_time), '00:04:22') You can add comments like this to indicate what your unittest is doing. But what flag do you have to add when running the file to see these comments?

-v python3 time-converter.py -v

You can close a file using the _______ method. You can check if a file is closed using the _________ attributed. Once closed, a file _________ (can/cannot) be read again.

.close() closed cannot

Using DictWriter for CSVs involves the following four steps: 1) __________ - creates a writer object for writing using dictionaries 2) __________ - kwarg for the DictWriter specifying headers 3) __________ - method on a writer to write header row 4) __________ - method on a writer to write row based on a dictionary

1) DictWriter 2) fieldnames 3) writeheader 4) writerow

Why should we write tests? 1) Reduce ___________ in existing code 2) Ensure bugs that are __________ stay that way 3) Ensure that new __________ don't break old ones 4) Ensure that ________ doesn't introduce new bugs 5) Makes development more ________?

1) bugs 2) fixed 3) features 4) refactoring (or cleanup) 5) fun

"a" (append) writes to the end of a file no matter what. "r+" writes to the _____________ by default, but you can move it around via the cursor/seek. A) end B) beginning

B

Calling .read() on a file object tells Python to read that file. It does this by using a cursor. After reading a file, the cursor is where? A) The beginning B) The end C) Nowhere (it's done reading)

B

The built-in open() function returns what? A) a string B) a file object

B

def add_positive_numbers(x, y): # your code here What is the correct way of "asserting" both x and y are positive? A) assert(x > 0 and y > 0, "Both numbers must be positive!") B) assert x > 0 and y > 0, "Both numbers must be positive!"

B

TDD generally follows the ____, _____, _____ model. 1) ____ - write a test that fails 2) ____ - write the minimal amount of code necessary to make the test pass 3) _____ - clean up the code, while ensuring the tests still pass

Red/Green/Refactor

f = open("story.txt") What class is f right now?

TextIOWrapper

True or False: "a" (append) mode will append always to the end, even if you use file.seek(0) first.

True

True or False: Although you can read CSV files like any other text file, Python has a built-in CSV module to read/write CSVs way more easily.

True

True or False: Decorators are functions.

True

True or False: doctests can be kinda fun using the REPL syntax in the docstring, but ultimately it proves to be too finicky with things like single-quotes vs double-quotes, white space, dictionary order, and error callbacks.

True

True or False: setUp() and tearDown() must be called exactly that and placed inside the Test class in order to have their proper effect.

True

True or False: You can read CSV files just like any other text files.

True (Although it's far from the best way.)

True or False: Just like text files with FileIO, if you write to a CSV file that doesn't exist, it will create one for you.

True with ("cats.csv", "w") as file: csv_writer = writer(file) file.writerow(["Name", "Age"]) file.writerow(["Blue", 3])

Can you pass an argument to a decorator? @some_decorator("blessing") def some_function(): pass

Yes See video: https://www.udemy.com/the-modern-python3-bootcamp/learn/lecture/9072490#overview

Can you use decorators to enable type enforcement?

Yes See video: https://www.udemy.com/the-modern-python3-bootcamp/learn/lecture/9072508#overview

The @decorator_name function goes directly ___________ the function you want to "decorate".

above def be_polite(fn): // does something with fn() @be_polite def greet(): print('hello') Calling greet() now comes loaded with whatever is happening in be_polite(). It's the same as saying... polite_greet = be_polite(greet) polite_greet()

When testing, we can make simple assertions using the _________ keyword.

assert

To check for a specific type of error when using unittest, you can use self.______________()

assertRaises() (Note: the syntax of checking this is different.)

Python comes with a built-in module called unittest that features easy ability to create ___________ for your code.

assertions

pickle is a Python module that is named based on the idea of "pickling" vegetables to preserve them so they last much longer. In Python, you can pickle data, which converts that data to a _______ ____________ and saves it to a .__________ file.

byte stream .pickle

For every open() on a file, you should also have a _________, because this practice frees up system resources.

close()

Many people prefer "with" statements when reading files because the __________ method happens automatically.

close()

Suppose you have a CSV file where the data is separated by pipes instead of commas. csv_reader = reader(file) What could be added to ensure the data is properly parsed?

csv_reader = reader(file, delimiter="|")

When using the tearDown() method, it's really only applicable if you're inserting mock data into a ______________ that you want to delete after tests have run.

database

One example of a Higher Order Function is a ______________.

decorator

How could you write a decorator called "delay" that takes in a number of seconds and then delays whatever function it decorates by that amount of time? So... @delay(3) def say_hi(): return "hi" Would wait 3 seconds before executing say_hi()

def delay(timer): def inner(fn): @wraps(fn) def wrapper(*args, **kwargs): print("Waiting {}s before running {}".format(timer, fn.__name__)) sleep(timer) return fn(*args, **kwargs) return wrapper return inner

How could you write a decorator that ensures only integers are passed to whatever functions it will decorate?

def only_ints(fn): def wrapper(*args, **kwargs): if any([arg for arg in args if type(arg) != int]): return "Please only invoke with integers." return fn(*args, **kwargs) return wrapper

We can write tests for functions inside the docstring using __________.

doctests

Python's built-in CSV module has the following: __________ - lets you iterate over rows of the CSV as lists __________ - lets you iterate over rows of the CSV as OrderedDicts (a dictionary with order, unlike a regular dictionary)

reader DictReader

After opening a CSV file you run... csv_reader = reader(file) csv_reader is now a ________________ which can only be iterated upon _________.

reader object once

What method is used to read only one line of a file?

readline()

What method is used to read all lines at once, but places them in a list?

readlines()

After reading a file, Python places its cursor at the end. To move it, you can use the _________ method.

seek()

The important thing to note about pickling is that it __________________ the data. If you need that data to be readable/usable while it's stored (i.e., without "unpickling" it), that is going to be a problem.

serializes

With unittest, the _________ method runs *before* each test method, while the __________ method runs *after* each test method.

setUp() tearDown()

Much like FileIO, the CSV module uses the ________ syntax to open CSV files.

with from csv import reader with open("fighters.csv") as file: csv_reader = reader(file) for row in csv_reader: # each row is a list! print(row)

Let's say you have an object of a Cat class that has been jsonpickled in a "cats.json" file. You want to open this object back up for use. What syntax would you use?

with open("cats.json", "r") as file: data = file.read() unfrozen = jsonpickle.decode(data) print(unfrozen)

Let's say you have an object "c" that is an instance of a Cat class. c = Cat("Charles", "Tabby") You want to save this object for later using *jsonpickle*. What syntax would you use?

with open("cats.json", "w") as file: frozen = jsonpickle.encode(c) file.write(frozen)

Let's say you have an object "blue" that is an instance of a Cat class, saved inside a pickle file "cats.pickle". You want to open this object back up so it's readable in Python. What syntax would you use?

with open("pets.pickle", "rb") as file: zombie_blue = pickle.load(file) Note the "rb" instead of "r" means we're "reading binary".

Let's say you have an object "blue" that is an instance of a Cat class. blue = Cat("Blue", "Scottish Fold, "yarn") You want to save this object for later using pickle. What syntax would you use?

with open("pets.pickle", "wb") as file: pickle.dump(blue, file) Note the "wb" instead of "w" means we're "writing binary".

Much like reader and DictReader, you can write to CSV files with the Python CSV module's ___________ and __________ methods.

writer DictWriter

The method most commonly used with CSV writer is what?

writerow


संबंधित स्टडी सेट्स

Mod 23 The Roots of Prejudice and "Stereotype Threat"

View Set

Fill in the Blank Vocab Sentences

View Set

Art History II, Reading Assignment 5

View Set