5/14/2020

Python - OOP(Object-Oriented Programming) Class Variables

** OOP(Object-Oriented Programming) Class Variables

==========================================

class Employee:

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * 1.04)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

print(emp_1.pay)
emp_1.apply_raise()
print(emp_1.pay)

---------------------------------

50000
52000

---------------------------------

==========================================

class Employee:

raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * raise_amount)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

print(emp_1.pay)
emp_1.apply_raise()
print(emp_1.pay)

---------------------------------

   emp_1.apply_raise()

    self.pay = int(self.pay * raise_amount)
NameError: name 'raise_amount' is not defined

---------------------------------

==========================================

class Employee:

raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * Employee.raise_amount)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

print(emp_1.pay)
emp_1.apply_raise()
print(emp_1.pay)


---------------------------------

50000
52000

---------------------------------

==========================================

class Employee:

raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

print(emp_1.pay)
emp_1.apply_raise()
print(emp_1.pay)


---------------------------------

50000
52000

---------------------------------

==========================================

class Employee:

raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)


print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

---------------------------------

1.04
1.04
1.04

---------------------------------

==========================================

class Employee:

raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)



print(emp_1.__dict__)
print("-"*80)
print(Employee.__dict__)

---------------------------------

{'first': 'HAN', 'last': 'SeokDu', 'pay': 50000, 'email': 'HAN.SeokDu@company.com'}
--------------------------------------------------------------------------------
{'__module__': '__main__', 'raise_amount': 1.04, '__init__': , 'fullname': , 'apply_raise': , '__dict__': , '__weakref__': , '__doc__': None}
---------------------------------

==========================================

class Employee:

raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)




emp_1.raise_amount = 1.05

print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

---------------------------------

1.04
1.05
1.04

---------------------------------

==========================================

class Employee:

raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

emp_1.raise_amount = 1.05

print(emp_1.__dict__)

print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

---------------------------------

{'first': 'HAN', 'last': 'SeokDu', 'pay': 50000, 'email': 'HAN.SeokDu@company.com', 'raise_amount': 1.05}
1.04
1.05
1.04

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amount = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)


print(Employee.num_of_emps)

emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

print(Employee.num_of_emps)

---------------------------------

0
2

---------------------------------


Python - OOP(Object-Oriented Programming) Classes and Instances

** OOP Tutorial 1: Classes and Instances


==========================================

# Python Object-Oriented Programming

class Employee:
pass


emp_1 = Employee()
emp_2 = Employee()

print(emp_1)
print(emp_2)

---------------------------------

__main__.Employee object at 0x022CFF88
__main__.Employee object at 0x022CFFB8

---------------------------------

==========================================

# Python Object-Oriented Programming

class Employee:
pass


emp_1 = Employee()
emp_2 = Employee()

print(emp_1)
print(emp_2)


emp_1.first = 'HAN'
emp_1.last = 'SeokDu'
emp_1.email = 'HAN@company.com'
emp_1.pay = 50000


emp_2.first = 'KIM'
emp_2.last = 'Young'
emp_2.email = 'KIM@company.com'
emp_2.pay = 30000


print(emp_1.email)
print(emp_2.email)

---------------------------------

__main__.Employee object at 0x01D6FF88
__main__.Employee object at 0x01D6FFB8
HAN@company.com
KIM@company.com

---------------------------------
==========================================

# Python Object-Oriented Programming

class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

print(emp_1.email)
print(emp_2.email)

---------------------------------

HAN.SeokDu@company.com
KIM.Young@company.com

---------------------------------

==========================================


# Python Object-Oriented Programming

class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

print(emp_1.email)
print(emp_2.email)

print('{} {}'.format(emp_1.first, emp_1.last))

---------------------------------

HAN.SeokDu@company.com
KIM.Young@company.com
HAN SeokDu

---------------------------------

==========================================

# Python Object-Oriented Programming

class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)



print(emp_1.email)
print(emp_2.email)

print(emp_1.fullname())

---------------------------------

HAN.SeokDu@company.com
KIM.Young@company.com
HAN SeokDu

---------------------------------

==========================================

class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)


print(emp_2.fullname())

---------------------------------

KIM Young

---------------------------------

==========================================

class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname():
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)


print(emp_2.fullname())

---------------------------------

print(emp_2.fullname())
TypeError: fullname() takes 0 positional arguments but 1 was given

---------------------------------

==========================================

class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Young', 30000)

emp_1.fullname()
print(Employee.fullname(emp_1))

---------------------------------

HAN SeokDu

---------------------------------


5/13/2020

Python - Namedtuple

** Namedtuple - When and why should you use namedtuples?


==========================================

from collections import namedtuple

color = (55, 155, 255)


print(color[0])

---------------------------------

55

---------------------------------

==========================================

from collections import namedtuple

color = {'red' : 55, 'green' : 155, 'blue' : 255}


print(color['red'])

---------------------------------

55

---------------------------------


==========================================

from collections import namedtuple

Color = namedtuple('Color', ['red', 'green', 'blue'])

color = Color(55, 155, 255)


print(color[0])

---------------------------------

55

---------------------------------

==========================================

from collections import namedtuple

Color = namedtuple('Color', ['red', 'green', 'blue'])

color = Color(55, 155, 255)


print(color.red)


---------------------------------

55

---------------------------------

==========================================

from collections import namedtuple

Color = namedtuple('Color', ['red', 'green', 'blue'])

dict_color = {'red': 55, 'green': 155, 'blue': 255}

color = Color(55, 155, 255)
white = Color(255, 255, 255)


print(white.blue)

---------------------------------

255

---------------------------------

==========================================

from collections import namedtuple

Color = namedtuple('Color', ['red', 'green', 'blue'])

dict_color = {'red': 55, 'green': 155, 'blue': 255}

color = Color(55, 155, 255)
white = Color(255, 255, 255)


print(dict_color['blue'])

---------------------------------

255

---------------------------------


Python - Decorators With Arguments

** Decorators With Arguments


==========================================

def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print('Executed After', original_function.__name__, '\n')
return result
return wrapper_function


@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))


display_info('John', 25)
display_info('Travis', 30)

---------------------------------

Executed Before display_info
display_info ran with arguments (John, 25)
Executed After display_info

Executed Before display_info
display_info ran with arguments (Travis, 30)
Executed After display_info

---------------------------------

==========================================

def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function

@prefix_decorator('TESTING:')
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))


display_info('John', 25)
display_info('Travis', 30)

---------------------------------

TESTING: Executed Before display_info
display_info ran with arguments (John, 25)
TESTING: Executed After display_info

TESTING: Executed Before display_info
display_info ran with arguments (Travis, 30)
TESTING: Executed After display_info

---------------------------------

==========================================

def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function

@prefix_decorator('LOG:')
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))


display_info('John', 25)
display_info('Travis', 30)

---------------------------------

LOG: Executed Before display_info
display_info ran with arguments (John, 25)
LOG: Executed After display_info

LOG: Executed Before display_info
display_info ran with arguments (Travis, 30)
LOG: Executed After display_info

---------------------------------


Python - Decorators - Dynamically Alter The Functionality Of Your Functions

** Decorators - Dynamically Alter The Functionality Of Your Functions


==========================================

def outer_function():
message = 'Hi'

def inner_function():
print(message)

return inner_function()

outer_function()

---------------------------------

Hi

---------------------------------

==========================================

# Decorators

def outer_function():
message = 'Hi'

def inner_function():
print(message)

return inner_function

outer_function()

---------------------------------

nothing

---------------------------------

==========================================

def outer_function():
message = 'Hi'

def inner_function():
print(message)

return inner_function

my_func = outer_function()
my_func()
my_func()
my_func()

---------------------------------

Hi
Hi
Hi

---------------------------------

==========================================

def outer_function(msg):
message = msg

def inner_function():
print(message)

return inner_function

hi_func = outer_function('Hi')
bye_func = outer_function('Bye')

hi_func()
bye_func()

---------------------------------

Hi
Bye

---------------------------------

==========================================

def outer_function(msg):
def inner_function():
print(msg)

return inner_function

hi_func = outer_function('Hi')
bye_func = outer_function('Bye')

hi_func()
bye_func()

---------------------------------

Hi
Bye

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function():
return original_function()
return wrapper_function


def display():
print('display function ran')

decorated_display = decorator_function(display)

decorated_display()

---------------------------------

display function ran

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function():
print('wrapper executed this befor'.format(original_function.__name__))
return original_function()
return wrapper_function


def display():
print('display function ran')

decorated_display = decorator_function(display)

decorated_display()


---------------------------------

wrapper executed this befor
display function ran

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function():
print('wrapper executed this befor'.format(original_function.__name__))
return original_function()
return wrapper_function


@decorator_function
def display():
print('display function ran')

display()

---------------------------------

wrapper executed this befor
display function ran

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function():
print('wrapper executed this befor'.format(original_function.__name__))
return original_function()
return wrapper_function


@decorator_function
def display():
print('display function ran')


def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('John', 25)

---------------------------------

display_info ran with arguments (John, 25)

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function():
print('wrapper executed this befor'.format(original_function.__name__))
return original_function()
return wrapper_function


@decorator_function
def display():
print('display function ran')

@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('John', 25)

---------------------------------

display_info('John', 25)
TypeError: wrapper_function() takes 0 positional arguments but 2 were given

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('wrapper executed this befor'.format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function


@decorator_function
def display():
print('display function ran')

@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('John', 25)

display()

---------------------------------

wrapper executed this befor
display_info ran with arguments (John, 25)
wrapper executed this befor
display function ran

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('wrapper executed this befor'.format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function


class decorator_class(object):
def __init__(self, original_function):
self.original_function = original_function

def __call__(self, *args, **kwargs):
print('call method executed this before {}'.format(self.original_function.__name__))
return self.original_function(*args, **kwargs)


@decorator_class
def display():
print('display function ran')

@decorator_class
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('John', 25)

display()

---------------------------------

call method executed this before display_info
display_info ran with arguments (John, 25)
call method executed this before display
display function ran

---------------------------------

==========================================

def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('wrapper executed this befor'.format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function



@decorator_function
def display():
print('display function ran')

@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('John', 25)

display()

---------------------------------

wrapper executed this befor
display_info ran with arguments (John, 25)
wrapper executed this befor
display function ran

---------------------------------

==========================================

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


@my_logger
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('John', 25)


---------------------------------

display_info ran with arguments (John, 25)


-------display_info.log---------------

INFO:root:Ran with args: ('John', 25), and kwargs: {}

---------------------------------

==========================================

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


@my_logger
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('Hank', 30)

---------------------------------

display_info ran with arguments (Hank, 30)


-------display_info.log---------------

INFO:root:Ran with args: ('John', 25), and kwargs: {}
INFO:root:Ran with args: ('Hank', 30), and kwargs: {}

---------------------------------

==========================================

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


import time

@my_timer
def display_info(name, age):
time.sleep(1)
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('Hank', 30)


---------------------------------

display_info ran with arguments (Hank, 30)
display_info ran in: 1.0000507831573486 sec

---------------------------------

==========================================

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


import time

@my_timer
@my_logger
def display_info(name, age):
time.sleep(1)
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('Hank', 30)

---------------------------------

display_info ran with arguments (Hank, 30)
wrapper ran in: 1.0000500679016113 sec

-------display_info.log---------------

INFO:root:Ran with args: ('John', 25), and kwargs: {}
INFO:root:Ran with args: ('Hank', 30), and kwargs: {}
INFO:root:Ran with args: ('Hank', 30), and kwargs: {}

---------------------------------


==========================================

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


import time

@my_logger
@my_timer
def display_info(name, age):
time.sleep(1)
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('Hank', 30)

---------------------------------

display_info ran with arguments (Hank, 30)
display_info ran in: 1.0030512809753418 sec

---------wrapper.log----------------

INFO:root:Ran with args: ('Hank', 30), and kwargs: {}

---------------------------------

==========================================

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


import time

def display_info(name, age):
time.sleep(1)
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info = my_logger(my_timer(display_info))

print(display_info.__name__)

---------------------------------

wrapper

---------------------------------

==========================================

from functools import wraps

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

@wraps(orig_func)
def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

@wraps(orig_func)
def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


import time

@my_timer
@my_logger
def display_info(name, age):
time.sleep(1)
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info = my_timer(display_info)

print(display_info.__name__)

display_info('Hank', 30)

---------------------------------

display_info
display_info ran with arguments (Hank, 30)
display_info ran in: 1.000056505203247 sec
display_info ran in: 1.000056505203247 sec

---------------------------------

==========================================


from functools import wraps

def my_logger(orig_func):
import logging
logging.basicConfig(filename = '{}.log'.format(orig_func.__name__), level = logging.INFO)

@wraps(orig_func)
def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)

return wrapper


def my_timer(orig_func):
import time

@wraps(orig_func)
def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result

return wrapper


import time

@my_timer
@my_logger
def display_info(name, age):
time.sleep(1)
print('display_info ran with arguments ({}, {})'.format(name, age))

display_info('Tom', 22)

---------------------------------

display_info ran with arguments (Tom, 22)
display_info ran in: 1.001056432723999 sec

-------display_info.log---------------

INFO:root:Ran with args: ('Tom', 22), and kwargs: {}

---------------------------------


5/12/2020

Python - Generators - How to use them and the benefits you receive

** Generators - How to use them and the benefits you receive


==========================================

def square_numbers(nums):
result = []
for i in nums:
result.append(i*i)
return result

my_nums = square_numbers([1, 2, 3, 4, 5])

print(my_nums)

---------------------------------

[1, 4, 9, 16, 25]

---------------------------------

==========================================

def square_numbers(nums):
for i in nums:
yield (i*i)

my_nums = square_numbers([1, 2, 3, 4, 5])

print(my_nums)

---------------------------------

generator object square_numbers at 0x016DC9C8

---------------------------------

==========================================

def square_numbers(nums):
for i in nums:
yield (i*i)

my_nums = square_numbers([1, 2, 3, 4, 5])

print(next(my_nums))

---------------------------------

1

---------------------------------

==========================================

def square_numbers(nums):
for i in nums:
yield (i*i)

my_nums = square_numbers([1, 2, 3, 4, 5])

print(next(my_nums))
print(next(my_nums))
print(next(my_nums))
print(next(my_nums))
print(next(my_nums))

---------------------------------

1
4
9
16
25

---------------------------------

==========================================

def square_numbers(nums):
for i in nums:
yield (i*i)

my_nums = square_numbers([1, 2, 3, 4, 5])

print(next(my_nums))
print(next(my_nums))
print(next(my_nums))
print(next(my_nums))
print(next(my_nums))
print(next(my_nums))

---------------------------------

print(next(my_nums))
StopIteration

---------------------------------

==========================================

def square_numbers(nums):
for i in nums:
yield (i*i)

my_nums = square_numbers([1, 2, 3, 4, 5])

for num in my_nums:
print(num)

---------------------------------

1
4
9
16
25

---------------------------------

==========================================

my_nums = [x * x for x in [1, 2, 3, 4, 5]]

for num in my_nums:
print(num)

---------------------------------

1
4
9
16
25

---------------------------------

==========================================

my_nums = [x * x for x in [1, 2, 3, 4, 5]]

print(my_nums)

for num in my_nums:
print(num)

---------------------------------

[1, 4, 9, 16, 25]
1
4
9
16
25

---------------------------------

==========================================

my_nums = (x * x for x in [1, 2, 3, 4, 5])

print(my_nums)

for num in my_nums:
print(num)

---------------------------------

generator object genexpr at 0x0250C9C8
1
4
9
16
25

---------------------------------

==========================================

my_nums = (x * x for x in [1, 2, 3, 4, 5])

print(list(my_nums))

---------------------------------

[1, 4, 9, 16, 25]

---------------------------------

==========================================

C:\Users\purunet>pip install Pympler
Collecting Pympler
  Downloading Pympler-0.8.tar.gz (175 kB)
     |████████████████████████████████| 175 kB 252 kB/s
Building wheels for collected packages: Pympler
  Building wheel for Pympler (setup.py) ... done
  Created wheel for Pympler: filename=Pympler-0.8-py3-none-any.whl size=164719 s
ha256=a294448bf7bb1b6e4b657728323d0e926cf291e41e1dfd2107bf4f61edd874ba
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\2c\09\38\
7c8c5dc224099d3a7194d154a99093d429bb4bda18c241c4b5
Successfully built Pympler
Installing collected packages: Pympler
Successfully installed Pympler-0.8

==========================================

C:\Users\purunet>pip install psutil
Collecting psutil
  Downloading psutil-5.7.0-cp38-cp38-win32.whl (231 kB)
     |████████████████████████████████| 231 kB 234 kB/s
Installing collected packages: psutil
Successfully installed psutil-5.7.0

==========================================

C:\Users\purunet>pip install resource
Collecting resource
  Downloading Resource-0.2.1-py2.py3-none-any.whl (25 kB)
Collecting python-easyconfig>=0.1.0
  Downloading Python_EasyConfig-0.1.7-py2.py3-none-any.whl (5.4 kB)
Collecting JsonForm>=0.0.2
  Downloading JsonForm-0.0.2.tar.gz (2.4 kB)
Collecting JsonSir>=0.0.2
  Downloading JsonSir-0.0.2.tar.gz (2.2 kB)
Collecting PyYAML
  Downloading PyYAML-5.3.1-cp38-cp38-win32.whl (199 kB)
     |████████████████████████████████| 199 kB 251 kB/s
Requirement already satisfied: six in c:\users\purunet\appdata\roaming\python\py
thon38\site-packages (from python-easyconfig>=0.1.0->resource) (1.14.0)
Collecting jsonschema
  Downloading jsonschema-3.2.0-py2.py3-none-any.whl (56 kB)
     |████████████████████████████████| 56 kB 490 kB/s
Collecting pyrsistent>=0.14.0
  Downloading pyrsistent-0.16.0.tar.gz (108 kB)
     |████████████████████████████████| 108 kB 504 kB/s
Requirement already satisfied: setuptools in c:\users\purunet\appdata\local\prog
rams\python\python38-32\lib\site-packages (from jsonschema->JsonForm>=0.0.2->res
ource) (41.2.0)
Collecting attrs>=17.4.0
  Downloading attrs-19.3.0-py2.py3-none-any.whl (39 kB)
Building wheels for collected packages: JsonForm, JsonSir, pyrsistent
  Building wheel for JsonForm (setup.py) ... done
  Created wheel for JsonForm: filename=JsonForm-0.0.2-py3-none-any.whl size=3331
 sha256=1cc4d42590c96068142b60dde492165f473ab84f49c04c04dc94c963bf7b416d
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\27\f1\cd\
8320913c1525700582412597b77e0db1221dd351e2a74360b9
  Building wheel for JsonSir (setup.py) ... done
  Created wheel for JsonSir: filename=JsonSir-0.0.2-py3-none-any.whl size=4778 s
ha256=f25ad7884be1a9c4cdc231aaa3cb5aa58c886c3501d421f3a426c284b6f76f3b
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\db\8f\60\
243dd2c23b0c34ef061da9d9600029bc99f7444449644867da
  Building wheel for pyrsistent (setup.py) ... done
  Created wheel for pyrsistent: filename=pyrsistent-0.16.0-cp38-cp38-win32.whl s
ize=56579 sha256=7eb7cd8eaa27cf515608dc161a46e96d742fffe13a2bdd22446a51245f675a2
c
  Stored in directory: c:\users\purunet\appdata\local\pip\cache\wheels\17\be\0f\
727fb20889ada6aaaaba861f5f0eb21663533915429ad43f28
Successfully built JsonForm JsonSir pyrsistent
Installing collected packages: PyYAML, python-easyconfig, pyrsistent, attrs, jso
nschema, JsonForm, JsonSir, resource
Successfully installed JsonForm-0.0.2 JsonSir-0.0.2 PyYAML-5.3.1 attrs-19.3.0 js
onschema-3.2.0 pyrsistent-0.16.0 python-easyconfig-0.1.7 resource-0.2.1

==========================================

=======참고 people.py=======================

import mem_profile
import random
import time

names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']

print('Memory (Before): {}Mb'.format(mem_profile.memory_usage_resource()))

def people_list(num_people):
    result = []
    for i in xrange(num_people):
        person = {
                    'id': i,
                    'name': random.choice(names),
                    'major': random.choice(majors)
                }
        result.append(person)
    return result

def people_generator(num_people):
    for i in xrange(num_people):
        person = {
                    'id': i,
                    'name': random.choice(names),
                    'major': random.choice(majors)
                }
        yield person

t1 = time.clock()
people = people_list(1000)
t2 = time.clock()

# t1 = time.clock()
# people = people_generator(1000000)
# t2 = time.clock()

print('Memory (After) : {}Mb'.format(mem_profile.memory_usage_resource()))
print('Took {} Seconds'.format(t2-t1))


=======참고 mem_profile.py=======================

from pympler import summary, muppy
import psutil
import resource
import os
import sys

def memory_usage_psutil():
    # return the memory usage in MB
    process = psutil.Process(os.getpid())
    mem = process.get_memory_info()[0] / float(2 ** 20)
    return mem

def memory_usage_resource():
    rusage_denom = 1024.
    if sys.platform == 'darwin':
        # ... it seems that in OSX the output is different units ...
        rusage_denom = rusage_denom * rusage_denom
    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / rusage_denom
    return mem

==========================================

OS가 windows 면 Error 남.

import resource
ModuleNotFoundError: No module named 'resource'

==========================================



Python - F-Strings - How to Use Them and Advanced String Formatting

** F-Strings - How to Use Them and Advanced String Formatting


==========================================

first_name = 'HAN'
last_name = 'SeokDu'

sentence = 'My name is {} {}'.format(first_name, last_name)
print(sentence)

---------------------------------

My name is HAN SeokDu

---------------------------------

==========================================

first_name = 'HAN'
last_name = 'SeokDu'

sentence = f'My name is {first_name} {last_name}'
print(sentence)

---------------------------------

My name is HAN SeokDu

---------------------------------

==========================================

first_name = 'HAN'
last_name = 'SeokDu'

sentence = f'My name is {first_name.upper()} {last_name.upper()}'
print(sentence)

---------------------------------

My name is HAN SEOKDU

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = 'My name is {} and I am {} years old'.format(person['name'], person['age'])
print(sentence)

---------------------------------

My name is Jenn and I am 23 years old

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = f'My name is {person['name']} and I am {person['age']} years old'
print(sentence)

---------------------------------

sentence = f'My name is {person['name']} and I am {person['age']} years old'
                                     ^
SyntaxError: invalid syntax

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = f'My name is {person["name"]} and I am {person["age"]} years old'
print(sentence)

---------------------------------

My name is Jenn and I am 23 years old

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = f"My name is {person['name']} and I am {person['age']} years old"
print(sentence)

---------------------------------

My name is Jenn and I am 23 years old

---------------------------------

==========================================

calculation = f'4 times 11 is equal to {4 * 11}'
print(calculation)

---------------------------------

4 times 11 is equal to 44

---------------------------------

==========================================

for n in range(1, 11):
sentence = f'The value is {n}'
print(sentence)

---------------------------------

The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
The value is 6
The value is 7
The value is 8
The value is 9
The value is 10

---------------------------------

==========================================

for n in range(1, 11):
sentence = f'The value is {n:02}'
print(sentence)

---------------------------------

The value is 01
The value is 02
The value is 03
The value is 04
The value is 05
The value is 06
The value is 07
The value is 08
The value is 09
The value is 10

---------------------------------

==========================================

for n in range(1, 11):
sentence = f'The value is {n:04}'
print(sentence)

---------------------------------

The value is 0001
The value is 0002
The value is 0003
The value is 0004
The value is 0005
The value is 0006
The value is 0007
The value is 0008
The value is 0009
The value is 0010

---------------------------------

==========================================

pi = 3.14159265

sentence = f'Pi is equal to {pi}'
print(sentence)

---------------------------------

Pi is equal to 3.14159265

---------------------------------

==========================================

pi = 3.14159265

sentence = f'Pi is equal to {pi:.4f}'
print(sentence)

---------------------------------

Pi is equal to 3.1416

---------------------------------

==========================================

pi = 3.14159265

sentence = f'Pi is equal to {pi:.5f}'
print(sentence)

---------------------------------

Pi is equal to 3.14159

---------------------------------

==========================================

from datetime import datetime

birthday = datetime(1990, 1, 1)

sentence = f'Jenn has a birthday on {birthday}'
print(sentence)

---------------------------------

Jenn has a birthday on 1990-01-01 00:00:00

---------------------------------

==========================================

https://www.python.org/doc/

==========================================

from datetime import datetime

birthday = datetime(1990, 1, 1)

sentence = f'Jenn has a birthday on {birthday:%B %d, %Y}'
print(sentence)

---------------------------------

Jenn has a birthday on January 01, 1990

---------------------------------



Python - How to Set the Path and Switch Between Different Versions/Executables (Windows)

** How to Set the Path and Switch Between Different Versions/Executables (Windows)

==========================================

>>> import sys

>>> sys.executable
'C:\\Users\\purunet\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe'

---------------------------------

C:\Users\purunet>echo %path%

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind
owsPowerShell\v1.0\;C:\MinGW\bin;C:\Users\purunet\AppData\Local\Programs\Python\
Python38-32\Scripts\;C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\

---------------------------------

C:\Users\purunet>pip install django
Collecting django
  Downloading Django-3.0.6-py3-none-any.whl (7.5 MB)
     |████████████████████████████████| 7.5 MB 67 kB/s
Collecting sqlparse>=0.2.2
  Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB)
     |████████████████████████████████| 40 kB 107 kB/s
Collecting asgiref~=3.2
  Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB)
Requirement already satisfied: pytz in c:\users\purunet\appdata\local\programs\p
ython\python38-32\lib\site-packages (from django) (2020.1)
Could not build wheels for pytz, since package 'wheel' is not installed.
Installing collected packages: sqlparse, asgiref, django
Successfully installed asgiref-3.2.7 django-3.0.6 sqlparse-0.3.1

---------------------------------

C:\Users\purunet>pip install wheel
Collecting wheel
  Downloading wheel-0.34.2-py2.py3-none-any.whl (26 kB)
Installing collected packages: wheel
Successfully installed wheel-0.34.2

---------------------------------

C:\Users\purunet>pip install django
Requirement already satisfied: django in c:\users\purunet\appdata\local\programs
\python\python38-32\lib\site-packages (3.0.6)
Requirement already satisfied: pytz in c:\users\purunet\appdata\local\programs\p
ython\python38-32\lib\site-packages (from django) (2020.1)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\purunet\appdata\local
\programs\python\python38-32\lib\site-packages (from django) (0.3.1)
Requirement already satisfied: asgiref~=3.2 in c:\users\purunet\appdata\local\pr
ograms\python\python38-32\lib\site-packages (from django) (3.2.7)

---------------------------------

C:\Users\purunet>pip show django
Name: Django
Version: 3.0.6
Summary: A high-level Python Web framework that encourages rapid development and
 clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: c:\users\purunet\appdata\local\programs\python\python38-32\lib\site-pa
ckages
Requires: pytz, asgiref, sqlparse
Required-by:

---------------------------------

==========================================

import sys

print(sys.version)
print(sys.executable)

---------------------------------

3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)]
C:\Users\purunet\AppData\Local\Programs\Python\Python38-32\python.exe

---------------------------------


Python - Duck Typing and Asking Forgiveness, Not Permission (EAFP)

** Duck Typing and Asking Forgiveness, Not Permission (EAFP)


==========================================

# Duck Typing and Easier to ask forgiveness than permission (EAFP)

class Duck:

    def quack(self):
        print('Quack, quack')

    def fly(self):
        print('Flap, Flap!')


class Person:

    def quack(self):
        print("I'm Quacking Like a Duck!")

    def fly(self):
        print("I'm Flapping my Arms!")


def quack_and_fly(thing):
    pass
    # Not Duck-Typed (Non-Pythonic)
    if isinstance(thing, Duck):
        thing.quack()
        thing.fly()
    else:
        print('This has to be a Duck!')

    print()

d = Duck()
quack_and_fly(d)

p = Person()
quack_and_fly(p)


---------------------------------

Quack, quack
Flap, Flap!

This has to be a Duck!

---------------------------------

==========================================

# Duck Typing and Easier to ask forgiveness than permission (EAFP)

class Duck:

    def quack(self):
        print('Quack, quack')

    def fly(self):
        print('Flap, Flap!')


class Person:

    def quack(self):
        print("I'm Quacking Like a Duck!")

    def fly(self):
        print("I'm Flapping my Arms!")


def quack_and_fly(thing):
    thing.quack()
    thing.fly()
   
    print()

d = Duck()
quack_and_fly(d)

p = Person()
quack_and_fly(p)

---------------------------------

Quack, quack
Flap, Flap!

I'm Quacking Like a Duck!
I'm Flapping my Arms!

---------------------------------

==========================================

# Duck Typing and Easier to ask forgiveness than permission (EAFP)

class Duck:

    def quack(self):
        print('Quack, quack')

    def fly(self):
        print('Flap, Flap!')


class Person:

    def quack(self):
        print("I'm Quacking Like a Duck!")

    def fly(self):
        print("I'm Flapping my Arms!")

def quack_and_fly(thing):

# LBYL (Non-Pythonic)
    if hasattr(thing, 'quack'):
        if callable(thing.quack):
            thing.quack()

    if hasattr(thing, 'fly'):
        if callable(thing.fly):
            thing.fly()
   
    print()

d = Duck()
quack_and_fly(d)

p = Person()
quack_and_fly(p)

---------------------------------

Quack, quack
Flap, Flap!

I'm Quacking Like a Duck!
I'm Flapping my Arms!

---------------------------------

==========================================

# Duck Typing and Easier to ask forgiveness than permission (EAFP)

class Duck:

    def quack(self):
        print('Quack, quack')

    def fly(self):
        print('Flap, Flap!')


class Person:

    def quack(self):
        print("I'm Quacking Like a Duck!")

    def fly(self):
        print("I'm Flapping my Arms!")

def quack_and_fly(thing):

# EAFP (Pythonic)
    try:
        thing.quack()
        thing.fly()
        thing.bark()
       
    except AttributeError as e:
        print(e)
   
    print()

d = Duck()
quack_and_fly(d)

p = Person()
quack_and_fly(p)

---------------------------------

Quack, quack
Flap, Flap!
'Duck' object has no attribute 'bark'

I'm Quacking Like a Duck!
I'm Flapping my Arms!
'Person' object has no attribute 'bark'

---------------------------------

==========================================

person = {'name': 'Jess', 'age': 23, 'job': 'Programmer'}

# LBYL (Non-Pythonic)
if 'name' in person and 'age' in person and 'job' in person:
print("I'm {name}. I'm {age} years old and I am a {job}".format(**person))

else:
print("Missing some keys")


---------------------------------

I'm Jess. I'm 23 years old and I am a Programmer

---------------------------------

==========================================

person = {'name': 'Jess', 'age': 23}

# LBYL (Non-Pythonic)
if 'name' in person and 'age' in person and 'job' in person:
print("I'm {name}. I'm {age} years old and I am a {job}".format(**person))

else:
print("Missing some keys")


---------------------------------

Missing some keys

---------------------------------

==========================================

person = {'name': 'Jess', 'age': 23, 'job': 'Programmer'}

# EAFP (Pythonic)
try:
print("I'm {name}. I'm {age} years old and I am a {job}".format(**person))
except KeyError as e:
print("Missing {} key".format(e))

---------------------------------

I'm Jess. I'm 23 years old and I am a Programmer

---------------------------------

==========================================

person = {'name': 'Jess', 'age': 23}

# EAFP (Pythonic)
try:
print("I'm {name}. I'm {age} years old and I am a {job}".format(**person))
except KeyError as e:
print("Missing {} key".format(e))

---------------------------------

Missing 'job' key

---------------------------------

==========================================


my_list = [1, 2, 3, 4, 5, 6]

# Non-Pythonic
if len(my_list) >= 6:
print(my_list[5])
else:
print("That index does not exist")

---------------------------------

6

---------------------------------

==========================================

my_list = [1, 2, 3, 4, 5]

# Non-Pythonic
if len(my_list) >= 6:
print(my_list[5])
else:
print("That index does not exist")

---------------------------------

That index does not exist

---------------------------------

==========================================

my_list = [1, 2, 3, 4, 5, 6]

# Pythonic
try:
print(my_list[5])
except IndexError:
print("That index does not exist")

---------------------------------

6

---------------------------------

==========================================

my_list = [1, 2, 3, 4, 5]

# Pythonic
try:
print(my_list[5])
except IndexError:
print("That index does not exist")


---------------------------------

That index does not exist

---------------------------------

==========================================

# Example from the Python Docs

import os

my_file = "/tmp/test.txt"

# Race Condition
if os.access(my_file, os.R_OK):
with open(my_file) as f:
print(f.read())
else:
print("File can not be accessed")

---------------------------------

File can not be accessed

---------------------------------

==========================================

# Example from the Python Docs

import os

my_file = "/tmp/test.txt"

# No Race-Condition
try:
f = open(my_file)
except IOError as e:
print("File can not be accessed")
else:
with f:
print(f.read())

---------------------------------

File can not be accessed

---------------------------------

Python - Except Blocks for Error Handling

** Using Try - Except Blocks for Error Handling


==========================================

f = open('testfile.txt')

try:
pass
except Exception:
pass

---------------------------------

    f = open('testfile.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'testfile.txt'

---------------------------------

==========================================

try:
f = open('testfile.txt')
except Exception:
print('Sorry. This file does not exist')

---------------------------------

Sorry. This file does not exist

---------------------------------

==========================================

try:
f = open('test_file.txt')
var = bad_var
except Exception:
print('Sorry. This file does not exist')

---------------------------------

Sorry. This file does not exist

---------------------------------

==========================================

try:
f = open('test_file.txt')
except FileNotFoundError as e:

print(e)
except Exception as e:
print(e)

---------------------------------

[Errno 2] No such file or directory: 'test_file.txt'

---------------------------------

==========================================

try:
f = open('test_file.txt')

except FileNotFoundError as e:
print(e)

except Exception as e:
print(e)

else:
print(f.read())
f.close()

---------------------------------

Test File Contents!

---------------------------------

==========================================

try:
f = open('test_file.txt')

except FileNotFoundError as e:
print(e)

except Exception as e:
print(e)

else:
print(f.read())
f.close()

finally:
  print("Executing Finally...")

---------------------------------

Test File Contents!
Executing Finally...

---------------------------------

==========================================


try:
f = open('currupt_file.txt')
if f.name == 'currupt_file.txt':
raise Exception

except FileNotFoundError as e:
print(e)

except Exception as e:
print('Error!')

else:
print(f.read())
f.close()

finally:
  print("Executing Finally...")


---------------------------------

[Errno 2] No such file or directory: 'currupt_file.txt'
Executing Finally...

---------------------------------