Python New Features
Python New Features
----------------------------
Python 3.8 ===>Oct 14th 2019
Python 3.9 ==>October 5th 2020
Python 3.8
This operator released as the part of PEP 572.
PEP-->Python Enhancement Proposals
l = [10,20,30,40,50]
n = len(l)
if n > 3:
print('List contains more than 3 elements')
print('The length of the list is:',n)
l = [10,20,30,40,50]
if len(l) > 3:
print('List contains more than 3 elements')
print('The length of the list is:',len(l))
l = [10,20,30,40,50]
if (n := len(l)) > 3:
print('List contains more than 3 elements')
print('The length of the list is:',n)
print(n)
heroines=[]
heroine=input('Enter Your Favourite Heroine:')
while heroine != 'done':
heroines.append(heroine)
heroine=input('Enter Your Favourite Heroine:')
print(heroines)
heroines=[]
while (heroine:=input('Enter Your Favourite Heroine:')) != 'done':
heroines.append(heroine)
print(heroines)
# read data line by line from abc.txt file and print to the console.
f=open('abc.txt')
line=f.readline()
while line != '':
print(line,end='')
line=f.readline()
f.close()
# read data line by line from abc.txt file and print to the console.
f=open('abc.txt')
while (line := f.readline()) != '':
print(line,end='')
f.close()
Positional-Only Parameter:
---------------------------
Python 3.8 Version
PEP 570
Functions:
-----------
1. Positional arguments
2. keyword arguments
3. default arguments
4. variable length arguments
1. Positional arguments:
order and number both are important
2. keyword arguments:
by keyword(parameter name)
The number of arguments must be matched
order is not important.
3. default arguments:
argumens with default values
after default argument, we cannot take non-default arguemnts
f1(a,b,*args,**kwargs):
keyword only parameters:
------------------------
After *, all paramters will become keyword only parameters.
At the time of calling we should pass values by keyword only.
def f1(*,a,b):
print(a,b)
f1(a=10,b=20) # valid
#f1(10,20) #TypeError: f1() takes 0 positional arguments but 2 were
given
f1(10,b=20) #TypeError: f1() takes 0 positional arguments but 1
positional argument (and 1 keyword-only argument) were given
def f1 (*,a=10,b=20)
def f1 (*,a=10,b=20):
print(a,b)
f1()
f1(a=10)
def f1 (*,a=10,b,c)
def f1(a,b,/):
print(a,b)
f1(10,20)
f1(a=10,b=20) #TypeError: f1() got some positional-only arguments
passed as keyword arguments: 'a, b'
f1(10,20,30,d=40,e=50,f=60)
#f1(10,b=20,c=30,d=40,e=50,f=60) #TypeError: f1() got some
positional-only arguments passed as keyword arguments: 'b'
f1(10,20,30,40,50,f=60) #TypeError: f1() takes 4 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were
given
sir what happen is fun(*, a ,b , c,/)
D:\durgaclasses>py test.py
File "D:\durgaclasses\test.py", line 1
def f1(*, a ,b , c,/):
^
SyntaxError: invalid syntax
def display(fullname,age,rollno):
print('Name:',fullname)
print('Age:',age)
print('RollNo:',rollno)
display('Ravi',14,101) # client/user
display(name='Ravi',age=14,rno=101) # client/user
display('Ravi',14,rno=101) # client/user
def display(fullname,age,rollno,/):
print('Name:',fullname)
print('Age:',age)
print('RollNo:',rollno)
display('Ravi',14,101) # client/user
case-2:
Assume parameter names are secured, we don't want to expose to
the outside world.
positional only parameters.
3. OOP
class Parent:
def m1(self,a,b):
print('Parent Method:',a+b)
class Child(Parent):
pass
c=Child()
c.m1(10,20)
D:\durgaclasses>py test.py
Parent Method: 30
class Parent:
def m1(self,a,b,/):
print('Parent Method:',a+b)
class Child(Parent):
def m1(self,x,y,/):
print('Child Method:',x+y)
c=Child()
c.m1(10,20)
4. performance improvement
5.
xyz(10,20,30)
xyz(a=10,b=20,c=30)
xyz(10,20,c=30)
xyz(10,b=20,c=30)
xyz(c=30,a=10,b=20)
/
*
Title: Python New Features- The Positional Only Parameter(/)
3 types of techniques
1. %-formatting
2. str.format() method
3. f-strings
1. %-formatting:
---------------
It is the oldest way of string formatting.
It is available from beginning of the python
o/p:
Hello Durga,Your Salary is 10000
Hello Durga,Your Salary is 10000
name='Aaradhya'
father_name='Abhishek'
mother_name='Aiswarya'
gf_name='Big B'
subject='Python'
s='Hello %s,You are most luckiest girl as you have %s,%s and %s as
family members,You can learn %s very easily'
%(name,father_name,mother_name,gf_name,subject)
print(s)
student = {
'name':'Aaradhya',
'father_name':'Abhishek',
'mother_name':'Aiswarya',
'gf_name':'Big B',
'subject':'Java'
}
s='Hello %s,You are most luckiest girl as you have %s,%s and %s as
family members,You can learn %s very easily'
%(student['name'],student['father_name'],student['mother_name'],st
udent['gf_name'],student['subject'])
print(s)
name='Durga'
salary=10000
gf='Sunny'
s1='Hello {},Your Salary is {},Your Girl Friend:{} is
waiting'.format(name,salary,gf)
s2='Hello {2},Your Salary is {1},Your Girl Friend:{0} is
waiting'.format(gf,salary,name)
s3='Hello {n},Your Salary is {s},Your Girl Friend:{g} is
waiting'.format(n=name,s=salary,g=gf)
print(s3)
student = {
'name':'Aaradhya',
'father_name':'Abhishek',
'mother_name':'Aiswarya',
'gf_name':'Big B',
'subject':'Java'
}
name='Aaradhya'
father_name='Abhishek'
mother_name='Aiswarya'
gf_name='Big B'
subject='Python'
s='Hello {n},You are most luckiest girl as you have {f},{m} and {g} as
family members,You can learn {s} very
easily'.format(n=name,f=father_name,m=mother_name,g=gf_name,s
=subject)
print(s)
name='Durga'
s1= 'Hello %s, Good Evening' %name
s2= 'Hello {}, Good Evening'.format(name)
s3= f'Hello {name}, Good Evening'
print(s3)
print(f'Hello {name}, Good Evening')
name='Durga'
salary=10000
gf='Sunny'
Hello Durga,Your Salary is 10000 and Your Girl Friend Sunny is waiting
Note: we can use either f or F, we can use single quotes or double
quotes or triple quotes also.
name='Durga'
salary=10000
gf='Sunny'
Hello Durga,Your Salary is 10000 and Your Girl Friend Sunny is waiting
Hello Durga,Your Salary is 10000 and Your Girl Friend Sunny is waiting
Hello Durga,Your Salary is 10000 and Your Girl Friend Sunny is waiting
Hello Durga,Your Salary is 10000 and Your Girl Friend Sunny is waiting
concise code,readability,speed
name='Durga'
salary=10000
gf='Sunny'
print('Hello %s, Your Salary is %d,Your Girl Friend %s is waiting'
%(name,salary,gf))
print('Hello {}, Your Salary is {},Your Girl Friend {} is
waiting'.format(name,salary,gf))
print(f'Hello {name}, Your Salary is {salary},Your Girl Friend {gf} is
waiting')
timeit module:
--------------
By using timeit module, we can measure execution time of small
coding snippets.
import timeit
t = timeit.timeit("print('Hello')",number=10000)
print(f'The Time Taken {t} seconds')
import timeit
t = timeit.timeit('''
name='Durga'
salary=10000
gf='Sunny'
s='Hello %s, Your Salary is %d,Your Girl Friend %s is waiting'
%(name,salary,gf)
''',number=100000)
print('The Time Taken:',t)
t = timeit.timeit('''
name='Durga'
salary=10000
gf='Sunny'
s='Hello {}, Your Salary is {},Your Girl Friend {} is
waiting'.format(name,salary,gf)
''',number=100000)
print('The Time Taken:',t)
t = timeit.timeit('''
name='Durga'
salary=10000
gf='Sunny'
s=f'Hello {name}, Your Salary is {salary},Your Girl Friend {gf} is waiting'
''',number=100000)
print('The Time Taken:',t)
output:
The Time Taken: 0.056381377999999996
The Time Taken: 0.07781707
The Time Taken: 0.037445747
name='Durga'
subject='Python'
print(f'''The classes of '{subject}' by "{name}" are too good ''')
The classes of 'Python' by "Durga" are too good
student = {
'name':'Aaradhya',
'father_name':'Abhishek',
'mother_name':'Aiswarya',
'gf_name':'Big B',
'subject':'Python'
}
s = f"Hello {student['name']}, You are the most luckiest girl as you
have {student['father_name']},{student['mother_name']} and
{student['gf_name']} as family members, You can learn
{student['subject']} very easily"
print(s)
name='Durga'
print(f'Faculty Name:{name.upper()}')
Faculty Name:DURGA
def mymax(a,b):
max=a if a>b else b
return max
a=int(input('Enter First Number:'))
b=int(input('Enter Second Number:'))
print(f'The Maximum of {a} and {b} is {mymax(a,b)}')
D:\durgaclasses>py test.py
Enter First Number:100
Enter Second Number:200
The Maximum of 100 and 200 is 200
def mymax(a,b,c):
max=a if a>b and a>c else b if b>c else c
return max
class Student:
def __init__(self,name,rollno,marks):
self.name=name
self.rollno=rollno
self.marks=marks
def __str__(self):
return
f'Name:{self.name},RollNo:{self.rollno},Marks:{self.marks}'
def __repr__(self):
return f'Student Name:{self.name},Student
RollNo:{self.rollno},Student Marks:{self.marks}'
s=Student('Ravi',101,90)
print('Information--->{}'.format(s)) #
print(f'Information --->{s}')
print(f'Information --->{s!r}')
D:\durgaclasses>py test.py
Information--->Name:Ravi,RollNo:101,Marks:90
Information --->Name:Ravi,RollNo:101,Marks:90
Information --->Student Name:Ravi,Student RollNo:101,Student
Marks:90
a=10
b=20
c=30
print(f'The Result:{10*20/3}')
print(f'The Result:{10*20/3:.2f}')
print(f'The Result:{a+b*c}')
D:\durgaclasses>py test.py
The Result:66.66666666666667
The Result:66.67
The Result:610
title: f-strings (formatted strings) 3.6 Version Enhancement Part-2
name='Durga'
print(f'Name:{name}') # Name:Durga
print(f'Name:{{name}}') #Name:{name}
print(f'Name:{{{name}}}') #Name:{Durga}
print(f'Name:{{{{name}}}}') #Name:{{name}}
Name:Durga
Name:{name}
Name:{Durga}
Name:{{name}}
3.6 version enhancements realted to f-string
x=10
y=20
print(f'{x=}')
print(f'{y=}')
Name='Durga'
Salary=10000
Girl_Friend_Name='Sunny'
print(f'{Name=},{Salary=},{Girl_Friend_Name=}')
Name='Durga',Salary=10000,Girl_Friend_Name='Sunny'
%-formatting
str.format()
performance
concise,less verbose,more readable
[email protected]
8885252627
8096969696
durgasoftonline.com
one doubt, can people with Naga Dhosh can also learn Python sir? :)
[email protected]
d={100:'Sunny',200:'Bunny',300:'Chinny'}
d[400]='Vinny'
d[100]='Zinny'
print(d)
l=[10,20,30,40,50]
t=(10,20,30,40,50)
s={10,20,30,40,50}
print(l) #[10,20,30,40,50]
print(t) #(10,20,30,40,50)
print(s) #{50, 20, 40, 10, 30}
d = OrderedDict()
d[100]='Sunny'
d[200]='Bunny'
d[300]='Chinny'
d[400]='Vinny'
d[500]='Pinny'
for k,v in d.items():
print(k,'---->',v)
d = {}
d[100]='Sunny'
d[200]='Bunny'
d[300]='Chinny'
d[400]='Vinny'
d[500]='Pinny'
print(d) #{100: 'Sunny', 200: 'Bunny', 300: 'Chinny', 400: 'Vinny', 500:
'Pinny'}
3.7 version
dict==>
l1=[10,20,30,40]
r=reversed(l1)
l2=list(r)
print('Original Order:',l1)
print('Reversed Order:',l2)
t1=(10,20,30,40)
r=reversed(t1)
t2=tuple(r)
print('Original Order:',t1)
print('Reversed Order:',t2)
But reversed() function not aaplicable for set and dict also.
s1={10,20,30,40}
r=reversed(s1) #TypeError: 'set' object is not reversible
From 3.8 version onwards, we can apply reversed() for dict also.
# merging operation
'''d3 = {**d1, **d2} #1st way
print(d1)
print(d2)
print(d3)
'''#update operation
d1.update(d2) # 1st way
print(d1)
print(d2)'''
From Python 3.9 version onwards , we can use | and |= operator for
dictionaries also.
l1=[10,20,30]
l2=[40,50,60]
l3=l1+l2 #1st way
print(l1)
print(l2)
print(l3)
l1=[10,20,30]
l2=[40,50,60]
l3=[*l1,*l2] #2nd way
print(l1)
print(l2)
print(l3)
BaseException
|-Exception
|-Warning
|-SyntaxWarning
l1= [10,20,30,40]
l2= [10,20,30,40]
print(l1 is l2)
print(l1 == l2)
10 and 10
l=[
[10,20,30]
[40,50,60]
[70,80,90]
]
print(l)
_ symbol in literal
Enum concept in python
continue inside finally
Type Hints
2. 96.3
in some engineering college-->KLCE VJA
8K--->96K
82 percentile
From Python 3.5 version onwards, we can declare the type explicitly
in python.
Static Type Checking is possible because of type hints(PEP 484).
We can declare the type for variables.
We can declare the type for function arguments.
We can declare the type for return values.
def add(x,y):
print(x+y)
#100 lines functionality
add(10,20)
add('durga','soft')
add({},{})
30
durgasoft
Traceback (most recent call last):
File "D:\durgaclasses\test.py", line 7, in <module>
add({},{})
File "D:\durgaclasses\test.py", line 2, in add
print(x+y)
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
2. mypy test.py
This command won't execute python program and it will perform
just static type checking.
add(10,20)
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
add(10,20)
add('durga','soft')
D:\durgaclasses>mypy test.py
test.py:6: error: Argument 1 to "add" has incompatible type "str";
expected "int"
test.py:6: error: Argument 2 to "add" has incompatible type "str";
expected "int"
Found 2 errors in 1 file (checked 1 source file)
add(10,20)
add('durga','soft')
add(10,'soft')
print(add.__annotations__)
{'x': <class 'str'>, 'y': <class 'str'>, 'return': <class 'str'>}
syntax:
variablename: type = value
a: int = 10
b: int = 20
c: bool = True
'''
ksjdfsajldsjlak
ksjdfsajldsjlak
ksjdfsajldsjlak
ksjdfsajldsjlak
ksjdfsajldsjlak
ksjdfsajldsjlak
ksjdfsajldsjlak
ksjdfsajldsjlak'''
print(__annotations__)
D:\durgaclasses>py test.py
{'a': <class 'int'>, 'b': <class 'int'>, 'c': <class 'bool'>}
ay they given like a:int = 10 this sir, y they did not mention like int a =
10, int b = 20 like java? is there any reason?
int a =10;
int b = 20;
a: float
a='durga'
print(a)
int,float,bool,str
Typing Library:
---------------
x: int = 10
def f1(x: str,y: int ) -> int:
pass
x: int = 10
x: float = 10.5
print(x) which one will come
D:\durgaclasses>py test.py
10.5
D:\durgaclasses>mypy test.py
test.py:2: error: Name 'x' already defined on line 1
Found 1 error in 1 file (checked 1 source file)
Python
Dynamically Typed Languages:
----------------------------
We are not required to declare the type explicitly.
The type will be considered automatically.
Easyness to the programmer.
def factorial(n):
if n<0:
return None
elif n==0:
return 1
else:
return n*factorial(n-1)
for i in range(11):
print(f'The factorial of {i} is:{factorial(i)}')
def factorial(n):
if n<0:
return None
elif n==0:
return 1
else:
return n*factorial(n-1)
for i in range(11):
print(f'The factorial of {i} is:{factorial(i)}')
print(factorial('durga'))
Type hints can be used for static type checking before execution.
def function_name(arg1,arg2):
pass
py test.py
Execute Python program
mypy test.py
It won't execute python program and just perform static type
checking
for i in range(11):
print(f'The factorial of {i} is:{factorial(i)}')
print(factorial('durga'))
D:\durgaclasses>mypy test.py
test.py:3: error: Incompatible return value type (got "None", expected
"int")
test.py:12: error: Argument 1 to "factorial" has incompatible type
"str"; expected "int"
Found 2 errors in 1 file (checked 1 source file)
for i in range(11):
print(f'The factorial of {i} is:{factorial(i)}')
print(factorial(6))
def f1(x,y,z):
pass
pincode = 500038
pincode: int = 500038
Sir, correct me if i am wrong, pyhton interpreter does not perform
type hints but python lang supports type hints. Is it not contradiction
names.append('durga')
names.append('ravi')
names.append('shiva')
names.append(10.5)
return names
# he is user
names = getnames()
for name in names:
print(f'{name} contains {len(name)} characters')
D:\durgaclasses>py test.py
durga contains 5 characters
ravi contains 4 characters
shiva contains 5 characters
Traceback (most recent call last):
File "D:\durgaclasses\test.py", line 13, in <module>
print(f'{name} contains {len(name)} characters')
TypeError: object of type 'float' has no len()
names.append('durga')
names.append('ravi')
names.append('shiva')
names.append(10)
return names
# he is user
names = getnames()
for name in names:
print(f'{name} contains {len(name)} characters')
D:\durgaclasses>mypy test.py
test.py:9: error: Argument 1 to "append" of "list" has incompatible
type "int"; expected "str"
Found 1 error in 1 file (checked 1 source file)
D:\durgaclasses>mypy test.py
test.py:3: error: List item 3 has incompatible type "int"; expected "str"
test.py:4: error: List item 3 has incompatible type "str"; expected "int"
test.py:5: error: List item 3 has incompatible type "int"; expected
"List[int]"
Found 3 errors in 1 file (checked 1 source file)
https://drive.google.com/drive/folders/1GgH7aFiCveMqc7S8P4c2Rcp
ncultqULb?usp=sharing
Title: Overview of Type Hints and Type Hints for List and Tuple
List,Tuple
l = [10,20,30,40]
t: Tuple[int,int,int] = (10,20,'durga')
print(t)
s: Set[int] = {10,20,30,40,'A'}
print(s)
test.py:3: error: Argument 5 to <set> has incompatible type "str";
expected "int"
Found 1 error in 1 file (checked 1 source file)
s: Set[int] = set()
s.add(10)
s.add(20)
s.add(30)
s.add('durga')
print(s)
test.py:7: error: Invalid index type "str" for "Dict[int, str]"; expected
type "int"
test.py:7: error: Incompatible types in assignment (expression has
type "int", target has type "str")
test.py:8: error: Incompatible types in assignment (expression has
type "int", target has type "str")
Found 3 errors in 1 file (checked 1 source file)
List,Tuple,Set,Dict
Sequence:
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
D:\durgaclasses>py test.py
durga
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
D:\durgaclasses>py test.py
[10, 20, 30, 40]
D:\durgaclasses>mypy test.py
test.py:3: error: Incompatible types in assignment (expression has
type "int", variable has type "Sequence[Any]")
Found 1 error in 1 file (checked 1 source file)
D:\durgaclasses>py test.py
10
f: Callable[[arg1Type,arg2Type],returntype]
f1(sum,10,20)
D:\durgaclasses>py test.py
30
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
from typing import Callable
def sum(a: str,b: str) -> None:
print(a+b)
f1(sum,'durga','soft')
D:\durgaclasses>py test.py
durgasoft
D:\durgaclasses>mypy test.py
test.py:6: error: Argument 1 has incompatible type "str"; expected
"int"
test.py:6: error: Argument 2 has incompatible type "str"; expected
"int"
test.py:8: error: Argument 1 to "f1" has incompatible type
"Callable[[str, str], None]"; expected "Callable[[int, int], None]"
Found 3 errors in 1 file (checked 1 source file)
from typing import Callable
def sum(a,b):
print(a+b)
f1(sum,10,20)
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
D:\durgaclasses>py test.py
30
x=10 or 10.5
f1(10)
f1(10.5)
f1('durga')
D:\durgaclasses>py test.py
10
10.5
durga
D:\durgaclasses>mypy test.py
test.py:7: error: Argument 1 to "f1" has incompatible type "str";
expected "Union[int, float]"
Found 1 error in 1 file (checked 1 source file)
x=10
print(x)
x=[10,20,30,40]
print(x)
x={100:'durga',200:'shiva'}
print(x)
x=(10,20,30)
D:\durgaclasses>mypy test.py
test.py:13: error: Incompatible types in assignment (expression has
type "Tuple[int, int, int]", variable has type "Union[List[Any], int,
Dict[Any, Any]]")
Found 1 error in 1 file (checked 1 source file)
D:\durgaclasses>py test.py
10
[10, 20, 30, 40]
{100: 'durga', 200: 'shiva'}
def factorial(n: int) -> int:
if n<0:
return None
elif n==0:
return 1
else:
return n*factorial(n-1)
for i in range(11):
print(f'The factorial of {i} is:{factorial(i)}')
for i in range(11):
print(f'The factorial of {i} is:{factorial(i)}')
Optional Type:
--------------
Union[int,None] --->Optional[int]--->Either int or None
Union[float,None] --->Optional[float]--->Either float or None
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
D:\durgaclasses>py test.py
10
None
from typing import Optional
def f1(x: int) -> int:
if x>10:
return None
else:
return x
f1(10)
f1(10)
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
f1(10)
D:\durgaclasses>mypy test.py
Success: no issues found in 1 source file
List,Tuple,Set,Dict,Sequence,Callable,Union,Optional
Pycharm
atom
vscode
eclipse
Advantages:
-----------
1. Type Hints helps to catch errors related to type.
2. Type Hints helps to document our code.
3. Type Hints improve IDE functionality
Limitations:
------------
1. Type hints take more developers time as we have to add type hints
explicitly.
2. Readability will be reduced as the length of the code increases
3. Type Hints will work only in newer versions
4. The startup time may increases if we use typing library.
e = Employee(100,'Sunny',10000,'Mumbai')
print(e.eno,e.ename,e.esal,e.eaddr)
print(e.__dict__)
D:\durgaclasses>py test.py
100 Sunny 10000 Mumbai
{'eno': 100, 'ename': 'Sunny', 'esal': 10000, 'eaddr': 'Mumbai'}
class Employee:
def __init__(self,eno,ename,esal,eaddr):
self.eno = eno
self.ename = ename
self.esal = esal
self.eaddr = eaddr
def __repr__(self):
return
f'Employee({self.eno},{self.ename},{self.esal},{self.eaddr})'
e1 = Employee(100,'Sunny',10000,'Mumbai')
e2 = Employee(200,'Bunny',20000,'Hyderabad')
print(e1)
print(e2)
D:\durgaclasses>py test.py
Employee(100,Sunny,10000,Mumbai)
Employee(200,Bunny,20000,Hyderabad)
class Employee:
def __init__(self,eno,ename,esal,eaddr):
self.eno = eno
self.ename = ename
self.esal = esal
self.eaddr = eaddr
def __repr__(self):
return
f'Employee({self.eno},{self.ename},{self.esal},{self.eaddr})'
e1 = Employee(100,'Sunny',10000,'Mumbai')
e2 = Employee(200,'Bunny',20000,'Hyderabad')
e3 = Employee(100,'Sunny',10000,'Mumbai')
print(e1 == e2) #False
print(e1 == e3) #True
o/p:
False
False
+ ----> __add__()
== --->__eq__()
class Employee:
def __init__(self,eno,ename,esal,eaddr):
self.eno = eno
self.ename = ename
self.esal = esal
self.eaddr = eaddr
def __repr__(self):
return
f'Employee({self.eno},{self.ename},{self.esal},{self.eaddr})'
def __eq__(self,other):
if self.eno == other.eno and self.ename == other.ename
and self.esal == other.esal and self.eaddr == other.eaddr:
return True
else:
return False
e1 = Employee(100,'Sunny',10000,'Mumbai')
e2 = Employee(200,'Bunny',20000,'Hyderabad')
e3 = Employee(100,'Sunny',10000,'Mumbai')
print(e1 == e2) #False
print(e1 == e3) #True
o/p:
D:\durgaclasses>py test.py
False
True
@dataclass
class Employee:
eno: int
ename: str
esal: int
eaddr: str
e1 = Employee(100,'Sunny',10000,'Mumbai')
e2 = Employee(200,'Bunny',20000,'Hyderabad')
e3 = Employee(100,'Sunny',10000,'Mumbai')
print(e1.eno,e1.ename,e1.esal,e1.eaddr)
print(e1)
print(e2)
print(e1 == e2)
print(e1 == e3)
D:\durgaclasses>py test.py
100 Sunny 10000 Mumbai
Employee(eno=100, ename='Sunny', esal=10000, eaddr='Mumbai')
Employee(eno=200, ename='Bunny', esal=20000, eaddr='Hyderabad')
False
True
@dataclass
class Employee:
eno: int
ename: str
esal: int
eaddr: str
@dataclass()
class Employee:
eno: int
ename: str
esal: int
eaddr: str
@dataclass(init=True,repr=True,eq=True,order=False,unsafe_hash=Fal
se, frozen=False)
class Employee:
eno: int
ename: str
esal: int
eaddr: str
@dataclass(repr=False,eq=False)
class Employee:
eno: int
ename: str
esal: int
eaddr: str
e1 = Employee(100,'Sunny',10000,'Mumbai')
e2 = Employee(200,'Bunny',20000,'Hyderabad')
e3 = Employee(100,'Sunny',10000,'Mumbai')
print(e1.eno,e1.ename,e1.esal,e1.eaddr)
print(e1)
print(e2)
print(e1 == e2)
print(e1 == e3)
D:\durgaclasses>py test.py
100 Sunny 10000 Mumbai
<__main__.Employee object at 0x000002A1C08E8160>
<__main__.Employee object at 0x000002A1C08E8E50>
False
False
The dataclass with frozen parameter( To create immutable classes):
-----------------------------------------------------------------
frozen means fixed and we cannot change.
The default value for frozen parameter is False.
If we set True, then we cannot change values of fields and become
constants.
@dataclass()
class Employee:
eno: int
ename: str
esal: int
eaddr: str
e1 = Employee(100,'Sunny',10000,'Mumbai')
e1.esal = 20000
print(e1)
D:\durgaclasses>py test.py
Employee(eno=100, ename='Sunny', esal=20000, eaddr='Mumbai')
from dataclasses import dataclass
@dataclass(frozen=True)
class Employee:
eno: int
ename: str
esal: int
eaddr: str
e1 = Employee(100,'Sunny',10000,'Mumbai')
e1.esal = 20000
print(e1)
D:\durgaclasses>py test.py
Traceback (most recent call last):
File "D:\durgaclasses\test.py", line 13, in <module>
e1.esal = 20000
File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'esal'
class Student:
def __init__(self,rollno,name,s1marks,s2marks,s3marks):
self.rollno=rollno
self.name=name
self.s1marks=s1marks
self.s2marks=s2marks
self.s3marks=s3marks
def __repr__(self):
return f'Student(rollno = {self.rollno},name =
{self.name},s1marks = {self.s1marks},s2marks =
{self.s2marks},s3marks = {self.s3marks})'
def __eq__(self,other):
return
(self.rollno,self.name,self.s1marks,self.s2marks,self.s3marks) ==
(other.rollno,other.name,other.s1marks,other.s2marks,other.s3marks
)
s1=Student(101,'Sunny',70,80,90)
s2=Student(101,'Sunny',70,80,90)
print(s1 == s2)
@dataclass
class Student:
rollno: int
name: str
s1marks: int
s2marks: int
s3marks: int
s1=Student(101,'Sunny',70,80,90)
s2=Student(101,'Sunny',70,80,90)
print(s1)
print(s2)
print(s1 == s2)
D:\durgaclasses>py test.py
Student(rollno=101, name='Sunny', s1marks=70, s2marks=80,
s3marks=90)
Student(rollno=101, name='Sunny', s1marks=70, s2marks=80,
s3marks=90)
True
Dataclass Parameters:
----------------------
@dataclass(init=True,repr=True,eq=True,order=False,unsafe_hash=Fal
se,frozen)
@dataclass(eq=False,order=True)
class Student:
rollno: int
name: str
s1marks: int
s2marks: int
s3marks: int
s1=Student(101,'Sunny',70,80,90)
s2=Student(101,'Sunny',70,80,90)
print(s1)
print(s2)
print(s1 == s2)
print(s1 < s2)
D:\durgaclasses>py test.py
Traceback (most recent call last):
File "D:\durgaclasses\test.py", line 4, in <module>
class Student:
File
"C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\da
taclasses.py", line 1013, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
File
"C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\da
taclasses.py", line 917, in _process_class
raise ValueError('eq must be true if order is true')
ValueError: eq must be true if order is true
@dataclass(frozen=True)
class Student:
rollno: int
name: str
s1marks: int
s2marks: int
s3marks: int
s1=Student(101,'Sunny',70,80,90)
s2=Student(101,'Sunny',70,80,90)
s1.s1marks=100
print(s1)
D:\durgaclasses>py test.py
Traceback (most recent call last):
File "D:\durgaclasses\test.py", line 14, in <module>
s1.s1marks=100
File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 's1marks'
@dataclass(frozen=True)
class Student:
rollno: int
name: str
s1marks: int =0
s2marks: int =0
s3marks: int =0
s1=Student(101,'Durga')
print(s1)
D:\durgaclasses>py test.py
Student(rollno=101, name='Durga', s1marks=0, s2marks=0,
s3marks=0)
Note: For any field, if we provide default value, then for all the
reamining fields compulsory we should provide default values
otherwise we will get TypeError.
@dataclass(frozen=True)
class Student:
rollno: int
name: str
s1marks: int =0
s2marks: int
s3marks: int =0
@dataclass
class Student:
rollno: int = field(repr=False)
name: str
s1marks: int
s2marks: int
s3marks: int
s1=Student(101,'Sunny',70,80,90)
print(s1)
D:\durgaclasses>py test.py
Student(name='Sunny', s1marks=70, s2marks=80, s3marks=90)
@dataclass
class Student:
rollno: int = field(repr=False)
name: str = field(init=False)
s1marks: int
s2marks: int
s3marks: int
s1=Student(101,'Sunny',70,80,90)
D:\durgaclasses>py test.py
Traceback (most recent call last):
File "D:\durgaclasses\test.py", line 12, in <module>
s1=Student(101,'Sunny',70,80,90)
TypeError: __init__() takes 5 positional arguments but 6 were given
Field Parameters:
-----------------
init: This field will be included in the generated __init__() method if
True.
Default value is True
@dataclass
class Student:
marks: List[int] = field(default_factory=list,
metadata={'max_marks_per_subject':100})
@dataclass
class Student:
rollno: int
name: str
s1marks: int = field(default=0)
s2marks: int
s3marks: int
s1=Student(101,'Sunny',70,80,90)
TypeError: non-default argument 's2marks' follows default argument
@dataclass
class Student:
marks: List[int] = field(default_factory=list)
s1=Student()
print(s1)
s2=Student([10,20,30,40])
print(s2)
D:\durgaclasses>py test.py
Student(marks=[])
Student(marks=[10, 20, 30, 40])
Python Logging:
---------------
Library
Lab
office
1. tracking
2.
log file
weblogic admin
Roope--->w7ejb1--->log file
complete flow
Exceptions information
It is highly recommended to store complete application flow and
exception information to a file. This process is called logging.
module: logging
logging levels:
---------------
depending on type of information, logging data is divided into the
following levels in python
1. CRITICAL --->50
Represents a very serious problem that needs high attention.
2. ERROR ---> 40
Represents a serious error
3. WARNING --->30
Represents a warning message, some caution needed. It is alert to
the programmer.
4. INFO --->20
Represents a message with some important information
5. DEBUG --->10
Represents a message which can be used for debugging
6. NOTSET --->0
Represents logging level not set
logging.basicConfig(filename='log.txt',level=logging.WARNING)
logging.basicConfig(filename='log.txt',level=30)
logging.debug(message)
logging.info(message)
logging.warning(message)
logging.error(message)
logging.critical(message)
Q. Write a python program to create a log file and write WARNING
and higher level messages?
import logging
logging.basicConfig(filename='log.txt',level=logging.WARNING)
logging.debug('Debug Message')
logging.info('Info Message')
logging.warning('Warning Message')
logging.error('Error Message')
logging.critical('Critical Message')
filemode='a'
filemode='w'
Default value for file mode: a means append
import logging
logging.basicConfig(format='%(levelname)s-%(message)s')
logging.critical('It is critical message')
logging.error('It is error message')
logging.warning('It is warning message')
logging.info('It is info message')
logging.debug('It is debug message')
28/11/2020 09:41:01 PM
import logging
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s'
,
datefmt='%d-%b-%Y,%A %I:%M %p')
logging.critical('It is critical message')
logging.error('It is error message')
logging.warning('It is warning message')
logging.info('It is info message')
logging.debug('It is debug message')
https://docs.python.org/3/library/time.html#time.strftime
https://docs.python.org/3/library/logging.html#logrecord-attributes
import logging
logging.basicConfig(
filename='mylog.txt',
level=logging.DEBUG,
format='%(asctime)s:%(levelname)s:%(message)s',
datefmt='%d-%m-%Y %I:%M %p'
)
logging.info('A New Request Came')
try:
x = int(input('Enter First Number:'))
y = int(input('Enter Second Number:'))
print('The Result:',x/y)
2. It will always work only for one handler either file or console but
not both simultaneously.
consoleHandler=logging.StreamHandler()
consoleHandler.setLevel(logging.ERROR)
eg1:
import logging
logger = logging.getLogger('demologger')
logger.setLevel(logging.DEBUG)
consoleHandler=logging.StreamHandler()
consoleHandler.setLevel(logging.ERROR)
formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-
%(message)s',
datefmt='%d-%m-%Y %I:%M:%S %p')
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
Note: Bydefault logger level will be available to handler. But we can
define our own level at handler level which will be the final for that
handler.
eg2:
import logging
logger = logging.getLogger('demologger')
logger.setLevel(logging.DEBUG)
fileHandler=logging.FileHandler('abc.log',mode='a')
fileHandler.setLevel(logging.ERROR)
formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-
%(message)s',
datefmt='%d-%m-%Y %I:%M:%S %p')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
eg3:
import logging
logger = logging.getLogger('demologger')
logger.setLevel(logging.DEBUG)
fileHandler=logging.FileHandler('abcd.log',mode='a')
fileHandler.setLevel(logging.ERROR)
consoleHandler=logging.StreamHandler()
consoleHandler.setLevel(logging.WARNING)
formatter1=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-
%(message)s',
datefmt='%d-%m-%Y %I:%M:%S %p')
formatter2=logging.Formatter('%(asctime)s-%(message)s',
datefmt='%d-%m-%Y %I:%M:%S %p')
fileHandler.setFormatter(formatter1)
consoleHandler.setFormatter(formatter2)
logger.addHandler(fileHandler)
logger.addHandler(consoleHandler)
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
fileHandler=logging.FileHandler('test.log',mode='a')
fileHandler.setLevel(logging.DEBUG)
formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-
%(message)s',
datefmt='%d-%m-%Y %I:%M:%S %p')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
student.py:
------------
import logging
logger = logging.getLogger('studentlogger')
logger.setLevel(logging.DEBUG)
fileHandler=logging.FileHandler('student.log',mode='w')
fileHandler.setLevel(logging.ERROR)
formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-
%(message)s',
datefmt='%d-%m-%Y %I:%M:%S %p')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
FrameInfo(
)
test.py
--------
from demo import getInfo
def f1():
getInfo()
f1()
demo.py:
---------
import inspect
def getInfo():
#print(inspect.stack())
#print(inspect.stack()[1])
print('Caller Module Name:',inspect.stack()[1][1])
print('Caller Function Name:',inspect.stack()[1][3])
custlogger.py:
-------------
import logging
import inspect
def get_custom_logger(level):
function_name = inspect.stack()[1][3]
logger_name = function_name+' logger'
logger = logging.getLogger(logger_name)
logger.setLevel(level)
fileHandler=logging.FileHandler('abc.log',mode='a')
fileHandler.setLevel(level)
formatter=logging.Formatter('%(asctime)s-%(name)s-
%(levelname)s-%(message)s',
datefmt='%d-%m-%Y %I:%M:%S %p')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
return logger
test.py:
-------
from custlogger import get_custom_logger
import logging
def logtest():
logger = get_custom_logger(logging.DEBUG) #logtest logger'
logger.debug('debug message from test module')
logger.info('info message from test module')
logger.warning('warning message from test module')
logger.error('error message from test module')
logger.critical('critical message from test module')
logtest()
student.py:
-----------
from custlogger import get_custom_logger
import logging
def logstudent():
logger = get_custom_logger(logging.ERROR) #logstudent logger
logger.debug('debug message from student module')
logger.info('info message from student module')
logger.warning('warning message from student module')
logger.error('error message from student module')
logger.critical('critical message from student module')
logstudent()
test.py:
--------
from custlogger import get_custom_logger
import logging
def f1():
logger = get_custom_logger(logging.DEBUG)
logger.debug('debug message from f1 function')
logger.info('info message from f1 function')
logger.warning('warning message from f1 function')
logger.error('error message from f1 function')
logger.critical('critical message from f1 function')
def f2():
logger = get_custom_logger(logging.WARNING)
logger.debug('debug message from f2 function')
logger.info('info message from f2 function')
logger.warning('warning message from f2 function')
logger.error('error message from f2 function')
logger.critical('critical message from f2 function')
def f3():
logger = get_custom_logger(logging.ERROR)
logger.debug('debug message from f3 function')
logger.info('info message from f3 function')
logger.warning('warning message from f3 function')
logger.error('error message from f3 function')
logger.critical('critical message from f3 function')
f1()
f2()
f3()
application
somewhere every activity we have to track
somewhere only important activity we have to track
project:
multiple modules
for every module maintain module specific log file
project:
For some modules File Handler is required
For some modules Console Handler is required
tkinter
mongodb
IDEs
numpy
pandas
matplotlib
logging_config.init:
--------------------
[loggers]
keys=root,demologger
[handlers]
keys=fileHandler
[formatters]
keys=sampleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler
[logger_demologger]
level=DEBUG
handlers=fileHandler
qualname=demologger
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=sampleFormatter
args=('test.log','w')
[formatter_sampleFormatter]
format=%(asctime)s:%(name)s:%(levelname)s:%(message)s
datefmt=%d-%m-%Y %I:%M:%S %p
import logging
import logging.config
logging.config.fileConfig("logging_config.init")
logger = logging.getLogger('demologger')
logger.critical('It is critical message')
logger.error('It is error message')
logger.warning('It is warning message')
logger.info('It is info message')
logger.debug('It is debug message')
[handlers]
keys=consoleHandler
[formatters]
keys=sampleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_demologger]
level=DEBUG
handlers=consoleHandler
qualname=demologger
[handler_consoleHandler]
class=StreamHandler
level=ERROR
formatter=sampleFormatter
args=(sys.stdout,)
[formatter_sampleFormatter]
format=%(asctime)s:%(name)s:%(levelname)s:%(message)s
datefmt=%d-%m-%Y %I:%M:%S %p
test.py:
-------
import logging
import logging.config
logging.config.fileConfig("logging_config.init")
logger = logging.getLogger('demologger')
logger.critical('It is critical message')
logger.error('It is error message')
logger.warning('It is warning message')
logger.info('It is info message')
logger.debug('It is debug message')