Featured Post

Keyword to create root window in python

lambda functions, errors and exceptions, Logging, Json in python - part 3


 

(8)LAMBDA:

#lambda arguments: expression

A lambda function is a small(one-line) anonymous function that is defined without a name.

 A lambda function can take any number of arguments, but can only have one expression.

To use lambda function type 'lambda' then it takes the argument and then evaluates it in the expression.


1.Adding two numbers.

for example:

add10 = lambda x: x + 10
print(add10(5))

output = 15


2.Multiplying two numbers.

for example:

mult = lambda x,y: x*y
print(mult(2,7))

output = 14  


3.Sort a list with lambda.

The key function transforms each element before sorting.

To sort the elements accordiing to the y value type '1' in the square brackets '[ ]' and to sort according to the x value type '0' in the square brackets '[ ]'.  

for example: 

points2d = [(12), (151), (51), (104)]
points2d_sortedy = sorted(points2d, key=lambda x: x[1])
print(points2d)
print(points2d_sortedy)

output = [(1, 2), (15, 1), (5, 1), (10, 4)]

[(5, 1), (15, 1), (1, 2), (10, 4)]

for example:

points2d = [(12), (151), (51), (104)]
points2d_sortedx = sorted(points2d, key=lambda x: x[0])
print(points2d)
print(points2d_sortedx)

output = [(1, 2), (15, 1), (5, 1), (10, 4)]

[(1, 2), (5, 1), (10, 4), (15, 1)]


4.Sorting with sum of each tuple.

for example:

points2d = [(12), (151), (51), (104)]
points2d_sorted = sorted(points2d, key=lambda x: x[0+ x[1])
print(points2d)
print(points2d_sorted)

output = [(1, 2), (15, 1), (5, 1), (10, 4)]

[(1, 2), (5, 1), (10, 4), (15, 1)]

5.Lambda inside another function:

In the example given below the variable 'n' in the function myfunc() is the variable used in the doubler and tripler variable which is 2 and 3.

for example: 

def myfunc(n):
    return lambda x: x * n

doubler = myfunc(2)
print(doubler(6))

tripler = myfunc(3)
print(tripler(6))

output = 

12
18

explanation:


6.Lambda function in custom key parameter:

The below is the an example of arranging the elements in the list with the 'abs()' function which means the absolute value of the variable this arranges the elements with its cojugate while arranging them in assanding order.

for example:

mylist = [- 1-4-2-31234]
print(sorted(mylist, key= lambda xabs(x)))

output = [-1, 1, -2, 2, -3, 3, -4]


7.Map function

# map(fun, seq)

transforms each element with 

for example: 

= [12345]

= map(lambda x: x*2, a)

print(list(b))

output = [2, 4, 6, 8, 10]


8.Filter function:

# filter(func, seq)

for example: 

= [12345, 6]

= map(lambda x: x%2==0, a)

print(list(b))

output = [2, 4, 6]

= [123456]
= [x for x in a if x%2==0]
print(b)

output = [2, 4, 6]

9.Reduce function: 

# reduce(func, seq)

for example: 

from functools import reduce

= [1234]

product_a = reduce(lambda x,y: x*y, a)

print(product_a)

output = 24




 

(9)ERRORS AND EXCEPTIONS:



A python program terminates as soon as it encounters an error the error could be a syntax error or exceptions.


1.Syntax error:

A syntax error occurs when there is an incorrect statement.

for example: 

= 5 print(a)

output = 

a = 5 print(a)

              ^

SyntaxError: invalid syntax


2.Type error: 

A type error occurs if an operation performed on an incorrect object type.

for example: 

= 5 + '10'

output = a = 5 + '10'

TypeError: unsupported operand type(s) for +: 'int' and 'str'


3.Module not found error:   

for example: 

import somemodule

output = 

import somemodule

ModuleNotFoundError: No module named 'somemodule'


4.Name error: 

A name error occurs when a name used is not defined.

for example:

= 5 

= c

output = b = c

NameError: name 'c' is not defined


5.File not found error:

A file not found error occurs when the code detects no such file you said to detect.

for example: 

= open('somefile.txt')

output = f = open('somefile.txt')

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


6.Value error:

for example: 

= [123]

a.remove(4)

print(a)

output =  a.remove(4)

ValueError: list.remove(x): x not in list


7.Index error: 

for example: 

= [1,2,3]

a[4]

print(a)

output = a[4]

IndexError: list index out of range


8.key error:

for example:

my_dict = {'name''Max'}

my_dict['age']

output =  my_dict['age']

KeyError: 'age'


9.Exceptions:

Raise an exeption by putting 

for example : 

= -1

if x < 0:
    raise Exception('x should be positive')   

output = raise Exception('x should be positive')

Exception: x should be positive

H

10.Assertion error:

for example:

= -1

assert (x>=0), 'x is not posintive'

output = assert (x>=0), 'x is not posintive'

AssertionError: x is not posintive


11.Try:

The ''try' function try's to run the code, and while running the code if there is an error it skip's it.It is helpful if you don't want to terminate you program while there is an error and want to continue.
If you want to run another code if the code in the try functions goes wrong you can use the 'except' function.

for example:

try:
    a = 5 / 0

except:
    print('an  error happend')

output = an error happened


To print a specific error.

for example: 

try:
    a = 5 / 0

except Exception as e:
    print(e)

output = division by zero 


To catch specific type of error type the type of error.

for example:

try:
    a = 5 / 1
    b = a + '10'

except ZeroDivisionError as e: 
    print(e)

except TypeError as e:
    print(e)

output = unsupported oprand type(s) for +: 'float and 'str'


If no error is there.

for example:

try:

   a = 5 / 1

   b = a + 10

except ZeroDivisionError as e: 

    print(e)

except TypeError as e:

    print(e)

else:
    print('evevrything is fine')

output = everything is fine


To do a task at the end of program no matter what happens use 'finally'.

for example:

try:
    a = 5 / 1
    b = a + 10

except ZeroDivisionError as e: 
    print(e)

except TypeError as e:
    print(e)

else:
    print('everything is fine')

finally:
    print('cleaning up...')

output = everything is fine

 cleaning up...  


try:

try:
   a = 5 / 0
   b = a + 10

except ZeroDivisionError as e: 
    print(e)

except TypeError as e:
    print(e)

else:
    print('everything is fine')

finally:
    print('cleaning up...')

output = division by zero

 cleaning up...


Making a custom error

for example:

class ValueTooHighError(Exception):
    pass

def test_value(x):

    if x >100:
        raise ValueTooHighError('value is too high')

test_value(200)

output  =  raise ValueTooHighError('value is too high')

__main__.ValueTooHighError: value is too high



 (10)LOGGING:



Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don't have any logging record and your program crashes, there are very few chances that you detect the cause of the problem. The logging module in Python is a powerful built-in module so you can quickly add logging to your application.

for example:  

import logging

logging.debug('This is a debug message')

logging.info('This is an info message')

logging. warning('This is a warning message')

logging.error('This is a error message')

logging.critical('This is a critical message')

output = WARNING:root: This is a warning message

   ERROR:root: This is an error message

 CRITICAL:root: This is a critical message


As we can see only warning, error, and critical are printed because these are defaults so if you want to change this it can be done by setting the basic configuration. To set the basic configuration import logging the type 'logging.basicConfig'then set the level format and default. 

To see more information go to-  https://docs.python.org/3/library/logging.html


1.Logging basic usage:

You can customize your root logger with the 'basicConfig'. The most common parameters are level, format, and filename.

for example:

import logging

logging.basicConfig(level=logging.DEBUGformat=
'%(asctime)s  %(name)s  %(levelname)s  %(message)s'datefmt='%m/%d/%Y %H:%M:%S')

logging.debug('This is a debug message')

logging.info('This is an info message')

logging.warning('This is a warning message')

logging.error('This is a error message')

logging.critical('This is a critical message')

output = 

02/22/2021 08:38:14  root  DEBUG  This is a debug message

02/22/2021 08:38:14  root  INFO  This is an info message

02/22/2021 08:38:14  root  WARNING  This is a warning message

02/22/2021 08:38:14  root  ERROR  This is an error message

02/22/2021 08:38:14  root  CRITICAL  This is a critical message


2.Making your own logger module:

First, make a .py file named helper then import logging module then make a variable named logger then use logging, and then using logging .getLogging(__name__) to name the module as the name of the py file. nd then setting the info given by the module 'logger.info('hello form helper')'


for example:

# helper.py
# -------------------------------------
import logging
logger = logging.getLogger(__name__)
logger.info('HELLO')

# main.py
# -------------------------------------
import logging
logging.basicConfig(level=logging.INFOformat='%(name)s - %(levelname)s - %(message)s')
import helper

# --> Output when running main.py
# helper - INFO - HELLO

output = 02/23/2021 08:04:12 - helper - INFO - hello form helper

helper.py:- 


main.py:- 




3.Propagate(spread and promote):

By default, all created loggers will pass the log events to the handlers of higher loggers, in addition to any handlers attached to the created logger. You can deactivate this by setting propagate = False.
Sometimes if you don't see a log message from another log this may be the reason for it.

for example:


main.py file:

import logging

logging.basicConfig(level=logging.DEBUGformat='%(asctime)s  %(name)s  %(levelname)s  %(message)s',
datefmt='%m/%d/%Y %H:%M:%S')

helper.py:

import logging

logger = logging.getLogger(__name__)

logger.propagate = False

logger.info('hello from helper')

output =


4.Log handler:

Log handlers are responsible for dispatching the appropriate log message to the handler's specific destination. You can use different log handlers to send the message to a standard output stream to files via HTTP or via email. To do this first we create a handler that logs to the stream and a file handler the file handler equals 'logging.FileHandler(file.log')' the 'file.log' is the name of the file, then we set the level and the format. We set the stream to only log messages of warning level and file to error level. With file_h = logging.FileHandler('file.log') you can create a log file in this file you will see the message __main__ - ERROR - this is an error

If you don't know about handlers check out this website:- https://docs.python.org/3/library/logging.handlers.html

for example:

import logging

logger = logging.getLogger(__name__)


stream_h = logging.StreamHandler()
file_h = logging.FileHandler('file.log')

stream_h.setLevel(logging.WARNING)
file_h.setLevel(logging.ERROR)

formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')

stream_h.setFormatter(formatter)
file_h.setFormatter(formatter)

logger.addHandler(stream_h)
logger.addHandler(file_h)

logger.warning('this is a warning')
logger.error('this is an error')

output = __main__ - WARNING - this is a warning

 __main__ - ERROR - this is an error


5.File config method:

First, you need to create a '.conf' file specify and it according to your configuration. Define the loggers, handlers, and formatters and provide the names as keys, after their names are defined, they are configured by adding the words logger, handler, and formatter before their names are defines.


.conf file:-


[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s


To use this config file we need to import it, and type 'logger.config.fileConfig('logging.conf')' and to get the logger use 'logging.getLogger('simpleExample').

for example:

import logging 
import logging.config

logging.config.fileConfig('logging.conf')

logger = logging.getLogger('simpleExample')

logger.debug('this is a debug message')

output = 2021-03-1 8:41:30,666 - simpleExample - DEBUG - this is a debug message


6.Capturing traceback message with logger:

To capture the traceback message 'use exc_info'.

for example:

import logging 

try:

    a = [1,2,3]

    val = a[4]

except IndexError as e:

    logging.error(e, exc_info=True)

output = 

ERROR:root: list index out of range

Traceback (most recent call last):

  File "d:/PycharmProjects/learn python by projects/venv/dictation.py", line 40, in <module>

    val = a[4]

IndexError: list index out of rangeT


If you don't know what error will be raised using the traceback module.


for example:

import logging 
import traceback

try:

    a = [1,2,3]

    val = a[4]

except IndexError as e:

    logging.error("The error is %s", traceback.format_exc())

output = 

ERROR:root:The error is Traceback (most recent call last):

  File "d:/PycharmProjects/learn python by projects/venv/dictation.py", line 41, in <module>

    val = a[4]

IndexError: list index out of range


7.Rotating file handler:

To keep track of the most recent log messages of an application.


for example:

import time
import logging
from logging.handlers import TimedRotatingFileHandler
 
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# This will create a new log file every minute, and 5 backup files with a timestamp before overwriting old logs.
handler = TimedRotatingFileHandler('timed_test.log'when='m'interval=1backupCount=5)
logger.addHandler(handler)
 
for i in range(6):
    logger.info('Hello, world!')
    time.sleep(50)


If your application is running for a long time you can use the 'TimedRotatingFileHandler'.this will create a rotating log base,

on how much time has passed. it can be set with the letters 's,m,h,d, midnight,w0,w1...' where s is seconds m is minutes 'h' is hours

d is days and w0 is Monday and you can set the other days of the week with the w and writing the number of the day as a number in front of 

the w.for example: w1 = Tuesday

the following code will create 5 log files having the text Hello, world!


for example:

import logging
import time
from logging.handlers import TimedRotatingFileHandler
 
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# This will create a new log file every minute, and 5 backup files with a timestamp 
before overwriting old logs.
handler = TimedRotatingFileHandler('timed_test.log'when='s'interval=1
backupCount=5)
logger.addHandler(handler)
 
for i in range(6):
    logger.info('Hello, world!')
    time.sleep(1)





 (11)JSON:

JSON is a short form for 'Java Script Object Notation' which is a text-based, human-readable data interchange format used for representing simple data structure and objects in web-browser-based code.

It is heavily used in web applications. Python comes with a build-in JSON module which makes it easy to work with

for example:



1.Encoding(serialization) and decoding JSON data:



To convert the python dictionary to JSON format import the JSON module then make a variable and store the command 'Jason.dumps(name of python dictionary)'.


for example:

import json

person = {"name""John""age"30"city""New York","hasChildren"False
"titles": ["engineer" ,"programmer"]}
personJSON = json.dumps(person)
print(personJSON)

output = {"name": "John", "age": 30, "city": "New York", "hasChildren": false, "titles": ["engineer", "programmer"]}


To convert JSON to python

for example:

import json
person_json = """
{
    "age": 30, 
    "city": "New York",
    "hasChildren": false, 
    "name": "John",
    "titles": [
        "engineer",
        "programmer"
    ]
}
"""
person = json.loads(person_json)
print(person)

output =

{'age': 30, 'city': 'New York', 'hasChildren': False, 'name': 'John', 'titles': ['engineer', 'programmer']}


To sort keys:

for example:

import json

person = {"name""John""age"30"city""New York","hasChildren"False"titles": ["engineer" ,"programmer"]}
personJSON = json.dumps(person, indent=4sort_keys=True)
print(personJSON)

output = 

{

    "age": 30,

    "city": "New York",

    "hasChildren": false,

    "name": "John",

    "titles": [

        "engineer",

        "programmer"

    ]

}


To open the text in a file. This will make a json file and will have the text converted from python dict to JSON.

for example:

import json

person = {"name""John""age"30"city""New York","hasChildren"False
"titles": ["engineer" ,"programmer"]}

personJSON = json.dumps(person, indent=4sort_keys=True)
print(personJSON)

with open('persons.json''w'as file:
    json.dump(person, file)

output = 

{

    "age": 30,

    "city": "New York",

    "hasChildren": false,

    "name": "John",

    "titles": [

        "engineer",

        "programmer"

    ]

}


person.json file:

{"name""John""age"30"city""New York""hasChildren"false"titles": ["engineer""programmer"]}


To decode JSON file back to python format.

for example:

 import json


person = {"name""John""age"30"city""New York","hasChildren"False"titles": ["engineer" ,"programmer"]}
personJSON = json.dumps(person, indent=4sort_keys=True)

person = json.loads(personJSON)
print(person)

output = 

{'age': 30, 'city': 'New York', 'hasChildren': False, 'name': 'John', 'titles': ['engineer', 'programmer']}


To decode variables in JSON.

for example:

import json

class User:
    def __init__(selfnameage):
        self.name = name
        self.age = age

user = User('Max'27)

def encode_user(o):
    if isinstance(o, User):
        return{'name': o.name, 'age':o.age, o.__class__.__name__: True}

    else:
        raise TypeError('object of type User is not JSON serializable')

    useJSON = json.dumps(user, defualt=encode_user)
    print(userJSON)

output = 

{"name": "Max", "age": 27, "User": true}

Comments