An Introduction to Metaclasses

Photo by Maxwell Nelson on Unsplash

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:
print(Tutorial())# Output -
# <__main__.Tutorial object at 0x7fd92c1500f0>

as we can see the instance of Tutorial class tells us that this is an object of…

Photo by Jamie Haughton on Unsplash

What is Monkey patching

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. …

Photo by chuttersnap on Unsplash

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 time
def timeit(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

Avoid Re-evaluation in Lists

Evaluating nums.append inside the loop

@timeit def append_inside_loop(limit): nums = [] for num in…

Photo by Markus Spiske on Unsplash

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
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] *…

How to use secure copy protocol

Photo by Laika Notebooks on Unsplash

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:

  • your local machine to a remote system
  • a remote system to your local system
  • one remote system to another remote system from your local system

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:

  • The…

Copy data in the right way to avoid bugs

Photo by Lysander Yuen on Unsplash

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.

  1. Assignment operator (=)
  2. Shallow copy
  3. Deep copy

Assignment Operator (=)

>>> 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…

Giving your functions defaults to work off of

Photo by Mitchell Luo on Unsplash.

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=[]):
return data

In this function, I set data to a list (mutable object) as a default argument. Now let's execute this function:


Understand how memory management works, even though you don’t have to do it yourself

Photo by Markus Spiske on Unsplash

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
  • A cycle-detecting algorithm (circular references)

Reference Counting

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…

Photo by Maxwell Nelson on Unsplash

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.

Pickle protocols:

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…

Photo by Markus Spiske on Unsplash

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 -

  • Single-Threaded
import time
from threading import Thread
COUNT = 50000000
def countdown(num):
while num > 0:
num -= 1
start = time.time()
end = time.time()
print('Time is taken by single_threaded - {} Sec.'.format(end - start))

Output -

Time is taken by single_threaded - 1.9384803771972656 Sec.
  • Multi-Threaded
import time
from threading import…

Prashant Sharma

Software Engineer | Python enthusiast |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store