From 762334f4a438abb36ba1fa51fe693575cbef6f2f Mon Sep 17 00:00:00 2001 From: stasDomb Date: Tue, 19 Feb 2019 06:59:37 +0200 Subject: [PATCH 1/8] adding functools.wraps for decorator task --- Lesson6FilesDecorators/DecoratorTask1.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Lesson6FilesDecorators/DecoratorTask1.py b/Lesson6FilesDecorators/DecoratorTask1.py index 55d1161..e2cd18c 100644 --- a/Lesson6FilesDecorators/DecoratorTask1.py +++ b/Lesson6FilesDecorators/DecoratorTask1.py @@ -1,8 +1,10 @@ # Задача-3 - не обязательна к выполнению # Написать декоратор который будет подавлять ошибки возникающие в теле вашей функции. +import functools def suppress_err(func): + @functools.wraps(func) def wrapper(): try: func() From d03be251f746f51b9c1293e255e6ec544940c3e3 Mon Sep 17 00:00:00 2001 From: stasDomb Date: Sun, 24 Feb 2019 20:21:15 +0200 Subject: [PATCH 2/8] First task was completed --- Lesson8ContexMan/Task1.py | 33 ++++++++++++++++++-------- Lesson8ContexMan/Task2.py | 4 ++++ Lesson8ContexMan/TaskExcOnPractice.py | 34 +++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 10 deletions(-) create mode 100644 Lesson8ContexMan/Task2.py create mode 100644 Lesson8ContexMan/TaskExcOnPractice.py diff --git a/Lesson8ContexMan/Task1.py b/Lesson8ContexMan/Task1.py index 86baec8..196bdbf 100644 --- a/Lesson8ContexMan/Task1.py +++ b/Lesson8ContexMan/Task1.py @@ -2,17 +2,30 @@ # в папку которую он принимает на вход. # Так же ваш объект должен принимать исключение которое он будет подавлять. # Если флаг об исключении отсутствует, исключение должно быть поднято. -# -#Нужно написать класс, который будет собирать информацию о погоде в регионе. -# API вы найдете на https://darksky.net/. -# Вам нужно сделать запрос на один из API представленныx в документации. -# Ваша задача подумать над тем как будет устроен ваш класс, -# какие методы он будет включать, где и как вы будете -# конфигурировать API, хранить ключ, обрабатывать респонс +import os -import request -class WeatherClass(object): - pass \ No newline at end of file +class ManageCont: + def __init__(self, path, excep, is_suppress=False): + self.path = path + self.saved_cwd = None # to save current dir + self.excep = excep + self.is_suppress = is_suppress + + def __enter__(self): + self.saved_cwd = os.getcwd() + try: + os.chdir(self.path) + except FileNotFoundError: + print("Path '{}' is not correct.".format(self.path)) + + def __exit__(self, *exc_info): + os.chdir(self.saved_cwd) + return self.is_suppress + + +with ManageCont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError, is_suppress=True): + raise KeyError + diff --git a/Lesson8ContexMan/Task2.py b/Lesson8ContexMan/Task2.py new file mode 100644 index 0000000..724ac0e --- /dev/null +++ b/Lesson8ContexMan/Task2.py @@ -0,0 +1,4 @@ +#Задача -2 +# Описать задачу выше но уже с использованием @contexmanager + + diff --git a/Lesson8ContexMan/TaskExcOnPractice.py b/Lesson8ContexMan/TaskExcOnPractice.py new file mode 100644 index 0000000..e02220b --- /dev/null +++ b/Lesson8ContexMan/TaskExcOnPractice.py @@ -0,0 +1,34 @@ +#Определить свой класс Exception +# который будет записывать месседж ошибки в файл. +# Тоесть при возникновении ошибки +# вам нужно писать ее в файл а не выводить. +# Как пример вызова вашего функционала используйте пример ниже: + +#try: +# some_func() +# except FormatError as exc: +# exc.logerror() + + +class SomeError(Exception): + + def __init__(self, line, file): + # line, file - where is exception was happened + self.line = line + self.file = file + + def write_log_to_file(self, logfile='file.txt'): + with open(logfile, 'a') as log_f: + log_f.write("Error at file {} in {}", self.file, self.line, file =log) + + +def test_func(): + raise SomeError(40, "compas.txt") + + +try: + test_func() +except SomeError as exc: + exc.write_log_to_file() + + From 7b189a7e7874f0c4d715c179d7bd323786861f17 Mon Sep 17 00:00:00 2001 From: stasDomb Date: Sun, 24 Feb 2019 21:47:01 +0200 Subject: [PATCH 3/8] Second and third tasks were completed, but I have the questions --- Lesson8ContexMan/Task1.py | 2 +- Lesson8ContexMan/Task2.py | 27 +++++++++++++++++++++++++++ Lesson8ContexMan/Task3_Time.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 Lesson8ContexMan/Task3_Time.py diff --git a/Lesson8ContexMan/Task1.py b/Lesson8ContexMan/Task1.py index 196bdbf..c4de2f9 100644 --- a/Lesson8ContexMan/Task1.py +++ b/Lesson8ContexMan/Task1.py @@ -10,7 +10,7 @@ class ManageCont: def __init__(self, path, excep, is_suppress=False): self.path = path - self.saved_cwd = None # to save current dir + self.saved_cwd = None # to save current dir self.excep = excep self.is_suppress = is_suppress diff --git a/Lesson8ContexMan/Task2.py b/Lesson8ContexMan/Task2.py index 724ac0e..da9b42b 100644 --- a/Lesson8ContexMan/Task2.py +++ b/Lesson8ContexMan/Task2.py @@ -1,4 +1,31 @@ #Задача -2 +#Создать объект менеджера контекста который будет переходить +# в папку которую он принимает на вход. +# Так же ваш объект должен принимать исключение которое он будет подавлять. +# Если флаг об исключении отсутствует, исключение должно быть поднято. # Описать задачу выше но уже с использованием @contexmanager +import os +import contextlib + + +@contextlib.contextmanager +def manage_cont(path,excep): + saved_cwd = os.getcwd() + try: + os.chdir(path) + except FileNotFoundError: + print("Path '{}' is not correct.".format(path)) + try: + yield {} + except excep as e: + print("error: {}".format(e)) + finally: + os.chdir(saved_cwd) + return excep + + +with manage_cont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError) as mc: + raise KeyError + diff --git a/Lesson8ContexMan/Task3_Time.py b/Lesson8ContexMan/Task3_Time.py new file mode 100644 index 0000000..f4397d7 --- /dev/null +++ b/Lesson8ContexMan/Task3_Time.py @@ -0,0 +1,33 @@ + +# Задача -3 +# Создать менеджер контекста который будет подсчитывать время выполняния блока инсрукций + +import time +import os + + +class ManageCont: + def __init__(self, path, excep, is_suppress=False): + self.path = path + self.saved_cwd = None # to save current dir + self.excep = excep + self.is_suppress = is_suppress + self.start_time = 0 + + def __enter__(self): + self.start_time = time.time() + self.saved_cwd = os.getcwd() + try: + os.chdir(self.path) + except FileNotFoundError: + print("Path '{}' is not correct.".format(self.path)) + + def __exit__(self, *exc_info): + os.chdir(self.saved_cwd) + print(time.time() - self.start_time) + return self.is_suppress + + +with ManageCont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError, is_suppress=True): + raise KeyError + From 8c968fb516614303aff413da87582de55283ef55 Mon Sep 17 00:00:00 2001 From: stasDomb Date: Thu, 28 Feb 2019 23:59:20 +0200 Subject: [PATCH 4/8] All tasks were modified. --- Lesson8ContexMan/Task1.py | 9 +++++---- Lesson8ContexMan/Task2.py | 17 +++++++++-------- Lesson8ContexMan/Task3_Time.py | 5 +++-- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/Lesson8ContexMan/Task1.py b/Lesson8ContexMan/Task1.py index c4de2f9..2e9e325 100644 --- a/Lesson8ContexMan/Task1.py +++ b/Lesson8ContexMan/Task1.py @@ -1,4 +1,4 @@ -#Создать объект менеджера контекста который будет переходить +# Создать объект менеджера контекста который будет переходить # в папку которую он принимает на вход. # Так же ваш объект должен принимать исключение которое он будет подавлять. # Если флаг об исключении отсутствует, исключение должно быть поднято. @@ -21,11 +21,12 @@ def __enter__(self): except FileNotFoundError: print("Path '{}' is not correct.".format(self.path)) - def __exit__(self, *exc_info): + def __exit__(self, exc_type, exc_val, exc_tb): os.chdir(self.saved_cwd) - return self.is_suppress + if exc_type is not None and issubclass(exc_type, self.excep): + return self.is_suppress -with ManageCont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError, is_suppress=True): +with ManageCont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError): raise KeyError diff --git a/Lesson8ContexMan/Task2.py b/Lesson8ContexMan/Task2.py index da9b42b..78960de 100644 --- a/Lesson8ContexMan/Task2.py +++ b/Lesson8ContexMan/Task2.py @@ -10,22 +10,23 @@ @contextlib.contextmanager -def manage_cont(path,excep): +def manage_cont(path, excep, is_suppress=False): saved_cwd = os.getcwd() try: os.chdir(path) - except FileNotFoundError: - print("Path '{}' is not correct.".format(path)) - try: yield {} - except excep as e: - print("error: {}".format(e)) + except excep: + print("Exception '{}' was raised".format(excep)) + finally: os.chdir(saved_cwd) - return excep + if is_suppress: + pass + else: + raise -with manage_cont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError) as mc: +with manage_cont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError,is_suppress=True) as mc: raise KeyError diff --git a/Lesson8ContexMan/Task3_Time.py b/Lesson8ContexMan/Task3_Time.py index f4397d7..0163c6f 100644 --- a/Lesson8ContexMan/Task3_Time.py +++ b/Lesson8ContexMan/Task3_Time.py @@ -22,10 +22,11 @@ def __enter__(self): except FileNotFoundError: print("Path '{}' is not correct.".format(self.path)) - def __exit__(self, *exc_info): + def __exit__(self, exc_type, exc_val, exc_tb): os.chdir(self.saved_cwd) print(time.time() - self.start_time) - return self.is_suppress + if exc_type is not None and issubclass(exc_type, self.excep): + return self.is_suppress with ManageCont(path="/Users/stas/PycharmProjects/PythonHomeworkDombrovskyi/", excep=KeyError, is_suppress=True): From e5b7881252fe85d88c663004a9b09ef7b30b62bf Mon Sep 17 00:00:00 2001 From: stasDomb Date: Sun, 3 Mar 2019 10:36:10 +0200 Subject: [PATCH 5/8] First task was finished --- Homework9Descriptor/PracticeTasks.py | 24 +++++++++++++++++++++ Homework9Descriptor/Task1.py | 31 ++++++++++++++++++++++++++++ Homework9Descriptor/__init__.py | 0 3 files changed, 55 insertions(+) create mode 100644 Homework9Descriptor/PracticeTasks.py create mode 100644 Homework9Descriptor/Task1.py create mode 100644 Homework9Descriptor/__init__.py diff --git a/Homework9Descriptor/PracticeTasks.py b/Homework9Descriptor/PracticeTasks.py new file mode 100644 index 0000000..1426cf3 --- /dev/null +++ b/Homework9Descriptor/PracticeTasks.py @@ -0,0 +1,24 @@ + +class Kilometers: + + def __get__(self, instance, owner): + return instance.m/1000 + + def __set__(self, instance, value): + instance.m =value/1000 + + +class Distance: + kilometers = Kilometers() + + def __init__(self, m): + self.m = m + + +distance = Distance(1200) + +print(distance.kilometers) +print(distance.m) + +distance.m = 2200 +print(distance.kilometers) \ No newline at end of file diff --git a/Homework9Descriptor/Task1.py b/Homework9Descriptor/Task1.py new file mode 100644 index 0000000..4893c1c --- /dev/null +++ b/Homework9Descriptor/Task1.py @@ -0,0 +1,31 @@ +# Задача-1 +# Реализовать дескриптор валидации для аттрибута email. +# Ваш дескриптор должен проверять формат email который вы пытаетесь назначить + +import re + + +class EmailDescriptor: + + def __init__(self, name="variable"): + self.name = name + + def __get__(self, instance, owner): + return instance.name + + def __set__(self, instance, value): + if re.fullmatch("[\w-]+@[\w-]+\.[\w-]+", value): + instance.name = value + else: + raise ValueError("it's not a valid email. Please, enter a valid email") + + +class MyClass: + email = EmailDescriptor() + + +my_class = MyClass() +# my_class.email = "valid-email@gmail.com" +# print(my_class.email) +# my_class.email = "novalidemail" + diff --git a/Homework9Descriptor/__init__.py b/Homework9Descriptor/__init__.py new file mode 100644 index 0000000..e69de29 From 74fc7fd0e7b331b5b20fd35caa2bfe5369a95c4b Mon Sep 17 00:00:00 2001 From: stasDomb Date: Sun, 3 Mar 2019 13:21:20 +0200 Subject: [PATCH 6/8] Small changes in the first task --- Homework9Descriptor/Task1.py | 2 +- Homework9Descriptor/Task3MetaClass.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 Homework9Descriptor/Task3MetaClass.py diff --git a/Homework9Descriptor/Task1.py b/Homework9Descriptor/Task1.py index 4893c1c..296564b 100644 --- a/Homework9Descriptor/Task1.py +++ b/Homework9Descriptor/Task1.py @@ -14,7 +14,7 @@ def __get__(self, instance, owner): return instance.name def __set__(self, instance, value): - if re.fullmatch("[\w-]+@[\w-]+\.[\w-]+", value): + if re.fullmatch("[\.\w-]+@[\.\w-]+", value): instance.name = value else: raise ValueError("it's not a valid email. Please, enter a valid email") diff --git a/Homework9Descriptor/Task3MetaClass.py b/Homework9Descriptor/Task3MetaClass.py new file mode 100644 index 0000000..2cc0ab8 --- /dev/null +++ b/Homework9Descriptor/Task3MetaClass.py @@ -0,0 +1,17 @@ +# Задача-2 +# Реализовать синглтон метакласс(класс для создания классов синглтонов). + +class Singleton(type): + + def __call__(cls, *args, **kwargs): + # your code here + pass + + +class MyClass(metaclass=Singleton): + pass + + +c = MyClass() +b = MyClass() +assert id(c) == id(b) \ No newline at end of file From c3cda4a6abbd4f5ec25f8a68ded33f901d5e835d Mon Sep 17 00:00:00 2001 From: stasDomb Date: Mon, 4 Mar 2019 23:34:17 +0200 Subject: [PATCH 7/8] Second task was finished --- Homework9Descriptor/Task1.py | 2 ++ .../{Task3MetaClass.py => Task2MetaClass.py} | 11 ++++++-- Homework9Descriptor/Task3Descr2.py | 28 +++++++++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) rename Homework9Descriptor/{Task3MetaClass.py => Task2MetaClass.py} (56%) create mode 100644 Homework9Descriptor/Task3Descr2.py diff --git a/Homework9Descriptor/Task1.py b/Homework9Descriptor/Task1.py index 296564b..805f423 100644 --- a/Homework9Descriptor/Task1.py +++ b/Homework9Descriptor/Task1.py @@ -20,6 +20,7 @@ def __set__(self, instance, value): raise ValueError("it's not a valid email. Please, enter a valid email") + class MyClass: email = EmailDescriptor() @@ -29,3 +30,4 @@ class MyClass: # print(my_class.email) # my_class.email = "novalidemail" + diff --git a/Homework9Descriptor/Task3MetaClass.py b/Homework9Descriptor/Task2MetaClass.py similarity index 56% rename from Homework9Descriptor/Task3MetaClass.py rename to Homework9Descriptor/Task2MetaClass.py index 2cc0ab8..d4bc031 100644 --- a/Homework9Descriptor/Task3MetaClass.py +++ b/Homework9Descriptor/Task2MetaClass.py @@ -1,11 +1,14 @@ # Задача-2 # Реализовать синглтон метакласс(класс для создания классов синглтонов). + class Singleton(type): + _instances = {} def __call__(cls, *args, **kwargs): - # your code here - pass + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] class MyClass(metaclass=Singleton): @@ -14,4 +17,6 @@ class MyClass(metaclass=Singleton): c = MyClass() b = MyClass() -assert id(c) == id(b) \ No newline at end of file +assert id(c) == id(b) +# print(id(c)) +# print(id(b)) diff --git a/Homework9Descriptor/Task3Descr2.py b/Homework9Descriptor/Task3Descr2.py new file mode 100644 index 0000000..a7067e2 --- /dev/null +++ b/Homework9Descriptor/Task3Descr2.py @@ -0,0 +1,28 @@ +# Задача-3 +# реализовать дескриптор IngegerField(), который будет хранить уникальные +# состояния для каждого класса где он объявлен + + +class IngegerField: + instances = {} + def __init__(self, value): + self.instances[self,None] = value + + def __get__(self, instance, owner): + return self.instances[self,owner] + + def __set__(self, instance, value): + self.instances[self,owner] = value + + +class Data: + number = IngegerField() + + +data_row = Data() +new_data_row = Data() + +data_row.number = 5 +new_data_row.number = 10 + +# assert data_row.number != new_data_row.number From 60271bec86ccef0772ed5f482054eaa1301b4a3f Mon Sep 17 00:00:00 2001 From: stasDomb Date: Sun, 10 Mar 2019 21:43:59 +0200 Subject: [PATCH 8/8] Third task of homework9 was finished --- Homework9Descriptor/Task3Descr2.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Homework9Descriptor/Task3Descr2.py b/Homework9Descriptor/Task3Descr2.py index a7067e2..14bee73 100644 --- a/Homework9Descriptor/Task3Descr2.py +++ b/Homework9Descriptor/Task3Descr2.py @@ -5,14 +5,15 @@ class IngegerField: instances = {} - def __init__(self, value): - self.instances[self,None] = value + + def __init__(self, value=None): + self.instances[self] = value def __get__(self, instance, owner): - return self.instances[self,owner] + return self.instances[self, instance] def __set__(self, instance, value): - self.instances[self,owner] = value + self.instances[self, instance] = value class Data: @@ -25,4 +26,4 @@ class Data: data_row.number = 5 new_data_row.number = 10 -# assert data_row.number != new_data_row.number +assert data_row.number != new_data_row.number