Python - LogeshVel/learning_resources GitHub Wiki
Single underscore and double underscore
list.sort() sorted(iterable)
fabs
abs (built in) - positive number fabs (provided by math module) - positive floating point number
format specifier
template string
Boolean type conversion
int(Boolean)
float(Boolean)
list(Boolean)
int attributes
dir()
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.
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.
help()
help gives the information about the python thing.
__name__ and __doc__
count words in doc
iter()
extended iter()
Extended iter and iter() are not the same. iter() takes iterable as the input whereas the extended iter(callable, end_match).
isinstance()
issubclass()
issubclass(ClassToChk, BaseClass))
Class
vars()
__dict__
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.
sys.path
The Python looks for the imported module in the system path variable.
PYTHONPATH
It is an environmental variable that has the system path from where the Python program will look for the modules.
absolute imports
Importing a module by giving the full path.
relative imports
Importing a module by giving the relative path from the current file.
Conditionals
lambda
callable
The callable() function returns True if the specified object is callable, otherwise it returns False.
*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
arguments after the *args must be passed as the key word argument else it will raise an error.
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.
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.
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.
Zip does the transposition. Converting rows to colums colums to row
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.
first class function
In Python, all fucntions are first class function. Meaning they are treated like any other object type.
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.
When the new binding happen it doesn't modifies the existing values of the different scopes
global
to modify the global variable values inside a function instead of creating new variable we could use the global keyword.
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
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..
The last function object result is compiled.
classes as decorators
instances as decorators
multiple decorators
First, nearby decorator is called and got the callable return and repeat the steps.
then,
finally,
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.
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.
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.)
static method (kindoff utility method)
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.
Trying to access the instance variable inside the static method
trying to access and modify the class variables
inheritance and overriding static method
Now, due to the explicit mention of which static method to use we lose our inheritance ability.
TO solve this,
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.
@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.
The property name should be always same (we can name anything but it should be same) in the highlighted places.
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.
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
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
property in inheritance
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.
properties and class methods
String representation of Python objects
str() and repr() functions for making string representations from Python objects which call the methods __str__() __repr__()
why do we need 2 methods?
repr()
str()
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.
__format__
ascii()
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.
chr()
float
Python float types can fail at many times due to precisions.
decimal
We can use decimal library to over come the issue faced by the Python float.
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.
abs()
The abs() function returns the absolute value of the specified number.
round()
bin() oct() int() hex()
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)
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)
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.
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.
Multiple Inheritance
Here Base1 class __init__
is called since it was the first preference while inheriting.
Method Resolution Order
MRO has some rules,
Here since the Class B and C inherits A, A has to come first before B for the Class D.
super()
class bound proxy
instance bound proxy
super() alone in the instance methods and class methods
then,
Collection Protocol
Exception
To handle the KeyError and IndexError we could use LookupError. Becasue both the KeyError and IndexError inheirts the LookupError.
e.args
our custom Exception
Custom Exception class with the overriding some methods.
raise Error() from e
Assertion
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)
Backend code of the Context manager
context manager protocol
custom Context manager class
enter()
exit()
The Exception is not propagated outside the with statement if the exit returns True.
contextlib
contextlib.contextmanager a decorator you can use to create new context managers.
The function shloud yield should not return