Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions students/swietczak_monika/lesson_14_decorators/authorization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
access_count = -1


def has_access():
"""
let's pretend this function calls some authorization services
returns True if access is granted and False if not
access is granted every 3rd time
"""
global access_count
access_count += 1
if access_count >= 3:
access_count = 0
return access_count == 0
13 changes: 13 additions & 0 deletions students/swietczak_monika/lesson_14_decorators/exercise1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def sort(some_function):
def sort_list():
return sorted(some_function())

return sort_list


@sort
def data_feeder():
return [4, 2, 1, 3]


print(data_feeder() == [1, 2, 3, 4]) # <- this is True
20 changes: 20 additions & 0 deletions students/swietczak_monika/lesson_14_decorators/exercise2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import authorization


def access_required(some_function):
def check_access(*args, **kwargs):
if authorization.has_access():
return some_function(*args, **kwargs)

return check_access


@access_required
def restricted_print(*args, **kwargs):
print(*args, **kwargs)


restricted_print('1 - visible')
restricted_print('2 - invisible')
restricted_print('3 - invisible')
restricted_print('4 - visible')
49 changes: 49 additions & 0 deletions students/swietczak_monika/lesson_14_decorators/exercise3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
def logger_wrapper(foo, *args, **kwargs):
print("Args: ")
for arg in args:
print(str(arg))

print("Kwargs: ")
for key, value in kwargs.items():
print("{} : {}".format(key, value))

foo(*args, **kwargs)


def logged(some_function):
def wrapper(*args, **kwargs):
# ("logger wrapper for function")
logger_wrapper(some_function, *args, **kwargs)

# print("Something after some_function() is called")

return wrapper


@logged
def just_some_function(*args, **kwargs):
print("Just some function with args: {}, kwargs: {}".format(args, kwargs))


@logged
def add_some_numbers(number_one, number_two):
print("Numbers added=", str(number_one + number_two))


@logged
def no_args_function():
print("No args function!")


def main():
some_dict = {'c': 2, 'd': 3}
just_some_function("a", "b", **some_dict)
just_some_function("a", "b")
just_some_function(**some_dict)
just_some_function()
add_some_numbers(1, 2)
no_args_function()


if __name__ == "__main__":
main()