An Introduction to Metaclasses
In most programming languages, classes are just pieces of code that define the rules for an object, but in Python, as you must hear that everything is an object: it turns out that this is true of classes themselves. classes are actually first-class objects, they can be created at runtime, passed as parameters, returned from functions, and assigned to variables.
let’s look at the below example -
class Tutorial:
passprint(Tutorial())# Output -
# <__main__.Tutorial object at 0x7fd92c1500f0>
as we can see the instance of Tutorial
class tells us that this is an object of…
In Python, the term monkey patch only refers to dynamic modifications of a class or module at runtime, which means monkey patch is a piece of Python code that extends or modifies other code at runtime.
Monkey patching can only be done in dynamic languages, of which python is a good example. In Monkey patching, we reopen the existing classes or methods in class at runtime and alters the behavior, which should be used cautiously, or you should use it only when you really need to. …
Today, we will be discussing the optimization technique in Python. In this article, you will get to know to speed up your code by avoiding the re-evaluation inside a list and dictionary.
Here I have written the decorator function to calculate the execution time of a function.
import functools
import timedef timeit(func):
@functools.wraps(func)
def newfunc(*args, **kwargs):
startTime = time.time()
func(*args, **kwargs)
elapsedTime = time.time() - startTime
print('function - {}, took {} ms to complete'.format(func.__name__, int(elapsedTime * 1000)))
return newfunc
let’s move to the actual function
Evaluating nums.append
inside the loop
@timeit def append_inside_loop(limit): nums = [] for num in…
A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code.
Let’s have a look at below example, suppose I want to calculate the Fibonacci of a number -
def fib_cal(fib_num, memo):
if memo[fib_num] is not None:
return memo[fib_num]
elif fib_num == 1 or fib_num == 2:
result = 1
else:
result = fib_cal(fib_num-1, memo) + fib_cal(fib_num-2, memo)
memo[fib_num] = result
return result
def get_fibonacci(fib_num): memo = [None] *…
The SCP (secure copy protocol) is a network protocol, based on the BSD RCP protocol, that supports file transfers between hosts on a network. SCP uses secure shell (SSH) for data transfer and the same mechanisms for authentication.
Using SCP, you can copy file/directory from:
While transferring data using SCP, files and passwords are encrypted so that anyone snooping on the traffic doesn’t get anything sensitive.
Things to keep in mind before you start:
Today, we will be discussing the copy in Python. There are three ways we can do it. In this article, you will get to know what each operation does and how they are different.
(=)
>>> a = [1, 2, 3, 4, 5]
>>> b = a
In the above example of the assignment operator, it does not make a copy of the Python objects. Instead, it copies a memory address (or pointer) from a
to b
, (b=a)
. Which means both a
and b
point to the same memory address.
Here, we can use…
Objects of built-in types like int
, float
, bool
, str
, tuple
, and Unicode
are immutable. Objects of built-in types like list
, set
, and dict
are mutable. A mutable object can change its state or contents, whereas immutable objects cannot.
This is a very simple definition of mutable and immutable objects in Python. Now for the interesting part, which is a mutable default object in function definitions.
I have written a very simple function below:
def foobar(element, data=[]):
data.append(element)
return data
In this function, I set data
to a list (mutable object) as a default argument. Now let's execute this function:
>>>…
In languages like C or C++, the programmer is responsible for the dynamic allocation and deallocation of memory on the heap. But in Python, programmers don’t have to preallocate or deallocate memory.
Python uses the following garbage-collection algorithms for memory management:
Reference counting is a simple procedure where referenced objects are deallocated when there’s no reference to them in a program.
In short, when the reference count becomes 0
, the object is deallocated (frees its allocated memory).
Let’s have a look at the below example:
def calculate_sum(num1, num2):
total = num1 + num2…
Pickling allows you to serialize and de-serializing Python object structures. In short, Pickling is a way to convert a python object into a character stream so that this character stream contains all the information necessary to reconstruct the object in another python script.
To successfully reconstruct the object, The Pickled byte stream contains instructions to the unpicker to reconstruct the original object structure along with instruction operands, which help in populating the object structure.
There are currently 6 different protocols that can be used for Pickling. The higher the protocol used, the more recent the version of Python needed to…
Any operation which is executed in the interpreter, GIL ensures that the interpreter is held by a single thread at a particular instant of time. it means that only one thread can be in a state of execution at any point in time.
Let’s take an example -
import time
from threading import ThreadCOUNT = 50000000
def countdown(num):
while num > 0:
num -= 1start = time.time()
countdown(COUNT)
end = time.time()print('Time is taken by single_threaded - {} Sec.'.format(end - start))
Output -
Time is taken by single_threaded - 1.9384803771972656 Sec.
import time
from threading import…
Software Engineer | Python enthusiast |