Decorators, Generators, Modules & Packages Flashcards
generator
(def. & how to define & what do they allow)
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
decorators
(definition, invoke, pause/stop execution, example)
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
Modules: Definition
.py script that you use in another .py script
Packages: Definition
files needed?
importing from package/subpackage?
call script from package?
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 (“.”)
if __name__ == “__main__”:
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