Decorators, Generators, Modules & Packages Flashcards

1
Q

generator

(def. & how to define & what do they allow)

A

function that retuns a lazy iterator (object that do not store their contents in memory)

use yield instead of return in the function block

def gen_func():

yeild value

——-

allows users to write a function that can send back a value, then later resume to pick up where it left off

they allow you to write a function that can send back a value and later reume a pick up where you left off

generate a sequence of values over time, instead of holding values in memory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

decorators

(definition, invoke, pause/stop execution, example)

A

defintion

  • creates a wrapper function for another function
  • allowing functionality to be added to the other function

Invoked:

@

Pause/Stop Execution

comment out the decorator

Example:

def dec_func(another_func):

def wrap_func():

print(‘Code Before Function: Top Wrap’)

another_func()

print(‘Code After Function: Bottom Wrap’)

return wrap_func

@dec_func #invokes the above decorator

def func_needs_dec():

print(‘I want to be decorated!!’)

func_needs_dec()

returns:

Code Before Function: Top Wrap.

I want to be decorated!!

Code After Function: Bottom Wrap

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Modules: Definition

A

.py script that you use in another .py script

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Packages: Definition

files needed?

importing from package/subpackage?

call script from package?

A

definition

collection of modules

files needed

__init__.py

lets python know this is a package and not a normal directory

needed in every folder where there is a module

importing packages

from package import script

from package.sub_package import sub_script

calling a script

package.function( )

sub_package.function( )

reference the package name before the period (“.”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

if __name__ == “__main__”:

A

used when importing function/data from a module

when modules are imported, it is used to bock or allow parts of code from being run

best explanation I’ve seen

https://www.freecodecamp.org/news/if-name-main-python-example/

come back too when building modules and packages

How well did you know this?
1
Not at all
2
3
4
5
Perfectly