Python - LogeshVel/learning_resources GitHub Wiki


Single underscore and double underscore

image

image

image

list.sort() sorted(iterable)

image

image

image

image

image

fabs

image

image

image

abs (built in) - positive number fabs (provided by math module) - positive floating point number

format specifier

formatted-string-literals

format-examples

image

image

image

image

image

template string

image

Boolean type conversion

int(Boolean)

image

float(Boolean)

image

list(Boolean)

image

int attributes

dir()

image

image

image

image

globals()

The globals() method returns a dictionary with all the global variables and symbols for the current program.

The globals() method doesn't take any parameters.

image

locals()

The locals() method returns a dictionary with all the local variables and symbols for the current program.

The locals() method doesn't take any parameters.

image

help()

help gives the information about the python thing.

image

__name__ and __doc__

image

count words in doc

image

iter()

image

extended iter()

image

image

image

Extended iter and iter() are not the same. iter() takes iterable as the input whereas the extended iter(callable, end_match).

isinstance()

image

image

image

issubclass()

issubclass(ClassToChk, BaseClass))

image

image

Class

image

image

image

image

image

vars()

image

image

__dict__

image

Modules and Packages

Packages and Modules are the way to organize the related code.

A module typically corresponds to a single source file, and you load modules into programs by using the import keyword. When you import a module, it is represented by an object of type module, and you can interact with it like any other object.

A package in Python is just a special type of module.

Packages are generally represented by **directories **in the file system, while modules are represented by single files.

Here fastapi is the Package. fastapi.middleware.cors is Module.

image

image

sys.path

The Python looks for the imported module in the system path variable.

image

PYTHONPATH

It is an environmental variable that has the system path from where the Python program will look for the modules.

docs

absolute imports

Importing a module by giving the full path.

image

image

relative imports

Importing a module by giving the relative path from the current file.

image

image

image

Conditionals

image

Conditional Expression

lambda

image

callable

The callable() function returns True if the specified object is callable, otherwise it returns False.

image

*args **kwargs

  • *args and **kwargs are special Python keywords that are used to pass the variable length of arguments to a function

  • When using them together, *args should come before **kwargs

  • The words “args” and “kwargs” are only a convention, you can use any name of your choice

image

image

image

image

image

arguments after the *args must be passed as the key word argument else it will raise an error.

image

Simply, in the function definition, the *args is the last parameter that is positional after this everything must be key word. **kwargs must be the last parameter in the function definition.

image

its all about packing and unpacking. * in the arguments is to say to unpack the iterable elements. if * is not specified at the time of calling the function with the iterables for the *args then it will take as the single positional arguments. Since we haven't specified to unpack the list or tuple that i sent as the individual positional arguments. Instead they are treated as the single positional argument.

* unpacks the iterables(list and tuple in our example) and calls the function and each element will be passed as the individual arguments.

image

The same goes for the **kwargs. we need to give ** while calling the function with the **kwargs paramater with the dict argument.

zip

To loop through the two or more iterable at the same time.

If one iterable contains more items, these items are ignored.

image

Zip does the transposition. Converting rows to colums colums to row

image

inner(local) function

The function defined inside another function is called inner function. That inner function is not an attribute of the outer function. The inner function is just an another function but that is defined inside a function.

image

first class function

In Python, all fucntions are first class function. Meaning they are treated like any other object type.

image

Closures

A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.

enclosing scope - the scope that encloses that

enclosing function - outer function

Firstly, a Nested Function is a function defined inside another function. It's very important to note that the nested functions can access the variables of the enclosing scope. However, at least in python, they are only readonly. However, one can use the "nonlocal" keyword explicitly with these variables in order to modify them. link

Closures maintains the reference to objects from earlier scopes.

Here the value of x is binded to the local fucntion but we haven't called that local function in its scope(inside the outer function). instead we have called that inner function from the global scope by making the outer fucntion to return the inner function. While doing so we need to remember the previous scope of that function to use the variable x while invoking that inner funtion outside of the outer function.

image

When the new binding happen it doesn't modifies the existing values of the different scopes

image

global

to modify the global variable values inside a function instead of creating new variable we could use the global keyword.

image

nonlocal

nonlocal keyword introduces the enclosing namespace variable to the local function (local namespace)

(introduces names from enclosing namespaces into the local namespace). You will get an error (SyntaxError) if the name doesn't exists

image

decorators

modify or enhance functions without changing their definition

The Decorator takes callable object and returns a callable object.

The callable can be of - class, function..

image

image

image

The last function object result is compiled.

image

classes as decorators

image

image

image

instances as decorators

image

image

image

multiple decorators

image

First, nearby decorator is called and got the callable return and repeat the steps.

image

then,

image

finally,

image

Attributes

class attributes

class attributes are class variables that are inherited by every object of a class.

The value of class attributes remain the same for every new object.

class attributes are defined outside the __init__() function.

instance attributes

Instance attributes, which are defined in the __init__() function, are instance variables that allow us to define different values for each object of a class.

image

image

image

class method

A class method is a method that is bound to the class and not the object of the class.

They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.

It can modify a class state that would apply across all the instances of the class.

For example, it can modify a class variable that will be applicable to all the instances.

A class method receives the class as an implicit first argument, just like an instance method receives the instance.

A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()).

Class method is intended to access, modify and work with the class attributes.

image

Class methods also used as the factory methods.

Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes. The Factory Method defines a method, which should be used for creating objects instead of using a direct constructor call ( new operator).

named constructor

Able to create instances.

have a class method that returns the object of the class. (which means we use this class method to create an object that is the contructor.)

image

static method (kindoff utility method)

Py Doc

Static methods in Python are extremely similar to Python class level methods, the difference being that a static method is also (like class method) bound to a class rather than the objects for that class.

This means that a static method can be called without an object for that class.

This also means that static methods cannot modify the state of an object as they are not bound to it.

We generally use static methods to create utility functions. like finding cubes, like that stuffs...only utilities

Static methods have a very clear use-case. When we need some functionality not with respect to an Object but with respect to the complete class, we make a method static. This is pretty much advantageous when we need to create Utility methods as they aren’t tied to an object lifecycle usually. Finally, note that in a static method, we don’t need the self to be passed as the first argument.

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()).

Simply, the Static method is a normal function inside the class. It has no self or cls parameter to be passed.

image

Trying to access the instance variable inside the static method

image

trying to access and modify the class variables

image

inheritance and overriding static method

image

Now, due to the explicit mention of which static method to use we lose our inheritance ability.

TO solve this,

image

here overriding of the static method works.

If it is explicit its done. we can't do anything.

static vs class vs instance methods

  • static method is the utility method inside the class and it doesnot modify the state of the class or instance.

  • class method deals with the class variables. and controls the state of the class across all the instances

  • instance method deals with the instance variables and stuffs. It doesnot intend to change the class state. only controls the instance state.

image

@property

To make the method as an attribute to access the value of the variable.

We can use the @property decorator on any method of a class and use the method as a property.

The @property decorator also makes the usage of getters and setters much easier/

  • Lets say we have to make the some attribute to be protected and not modified directly, and only get and set by the getters and setters.

image

image

The property name should be always same (we can name anything but it should be same) in the highlighted places.

image

image

Specifically, you can define three methods for a property:

  • A getter - to access the value of the attribute.
  • A setter - to set the value of the attribute.
  • A deleter - to delete the instance attribute.

image

You don't necessarily have to define all three methods for every property. You can define read-only properties by only including a getter method. You could also choose to define a getter and setter without a deleter.

We could do this job without the @property decorator but using the @property is more Pythonic way of doing it.

Providing Write-Only Attributes

image

image

Properties are the Pythonic way to create managed attributes in your classes.

By using the @property decorator we could create new attribute to the class. But by convention it should give some meaning(should manage the attributes)

Useful property method

image

property in inheritance

image

this raises the error in line 12. name 'person_age' is not defined

*The Property name is not inherited we need to explicitly specify that.

image

properties and class methods

image

String representation of Python objects

str() and repr() functions for making string representations from Python objects which call the methods __str__() __repr__()

image

why do we need 2 methods?

image

repr()

image

image

image

image

str()

image

image

image

Print(Obj) calls str() this calls repr()

If str() is not defined then calling print(Obj) it calls repr(). If defined then it calls the corresponding method.

image

image

image

__format__

image

image

image

image

ascii()

image

image

ord()

Python ord() and chr() are built-in functions. They are used to convert a character to an int and vice versa. Python ord() and chr() functions are exactly opposite of each other.

image

image

chr()

image

image

image

float

image

image

image

Python float types can fail at many times due to precisions.

image

image

decimal

We can use decimal library to over come the issue faced by the Python float.

image

image

The reason for the issue in Decimal(x)-Decimal(y) is that in Python the base 10, 0.8 value can't be exactly represented in base 2

So it is always recommended to use the quote literals to avoid this.

image

image

image

image

image

abs()

The abs() function returns the absolute value of the specified number.

image

round()

image

image

bin() oct() int() hex()

image

image

map()

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

map(function, iterables)

image

image

image

image

Map sequence terminated when one of the given sequence ends. In other words, the output of the map is the sequence whose len is equal to the smallest len of the input sequence.

filter()

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

filter(function, iterable)

image

image

reduce()

functools.reduce(function, iterable)

  • The first argument in reduce() is a function. This function will be applied to all the elements in an iterable in a cumulative manner to compute the result.

  • The second argument is iterable. Iterables are those python objects that can be iterated/looped over, includes like lists, tuples, sets, dictionaries, generators, iterator, etc.

image

In other words, reduce will reduce to sequence to the single value.

Ex: if we have list of numbers and if we pass the list to the reduce function that maps it to another fucntion so in the end the list is reduced to the single value as the ouptu of reduce.

image

Multiple Inheritance

image

Here Base1 class __init__ is called since it was the first preference while inheriting.

image

Method Resolution Order

image

image

image

MRO has some rules,

Here since the Class B and C inherits A, A has to come first before B for the Class D.

image

super()

image

image

image

class bound proxy

image

image

instance bound proxy

image

image

super() alone in the instance methods and class methods

image

image

then,

image

Collection Protocol

image

Ref

ABC

Exception

Exception Hierarchy

To handle the KeyError and IndexError we could use LookupError. Becasue both the KeyError and IndexError inheirts the LookupError.

image

e.args

image

our custom Exception

image

Custom Exception class with the overriding some methods.

image

raise Error() from e

image

Assertion

image

image

Context manager

A context manager usually takes care of setting up some resource, e.g. opening a connection, and automatically handles the clean up when we are done with it.

Simply, the Context manager does the setup and teardown parts.(enter and exit)

PEP

Backend code of the Context manager

image

image

image

context manager protocol

image

image

custom Context manager class

image

image

enter()

image

exit()

image

image

image

The Exception is not propagated outside the with statement if the exit returns True.

image

contextlib

image

contextlib.contextmanager a decorator you can use to create new context managers.

The function shloud yield should not return

image

image