Implementing in Python.

After releasing Python 3 we are hearing a lot about async and concurrency which can be achieved by asyncio module.But there are other ways to achieve asynchronous capability in python also, these are Threads and Processes .

Lets discuss basic terms we will use in this article.

Sync

In Synchronous operations, if you start more than one task, the tasks will be executed in sync, one after one.

Async

In asynchronous operations, if you start more than one task, all the tasks will be started immediately but will complete independently of one another. An async task may start and continue running while…


Python Implementation

In your development IDE, you might have noticed that it gives you error when you expression has missing enclosing brackets.How do they detect that closing bracket is missing ? Here I will write the solution as IDE does.

((10*5)+5 - missing brackets
{a+[c+(10*d)]} - ok
{x+[y+(z+d])} - missing brackets

Check the solution logic in HackerRank guide.I will just replicate this logic using stack(in python, it’s list) in code.

Output :

5
((10*5)+5
False
{a+[c+(10*d)]}
True
{x+[y+(z+d])}
False
{{[[(())]]}}
True


Django ORM optimization cheat sheet

Photo by Caspar Camille Rubin on Unsplash

In this piece I will run through a few key optimization tips rather that discussing on every point. Please read the Django official documentation for full details.

Throughout the piece we will use the following models :

class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()

def __str__(self):
return self.name

class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()

def __str__(self):
return self.name

class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
body_text = models.TextField(blank=True)
likes = models.IntegerField(blank=True, default=0)
authors = models.ManyToManyField(Author, blank=True)

class Meta:
default_related_name = 'entries'

def __str__(self):
return self.headline

Understand QuerySet Evaluation and Caching

Django developer must have an understanding of QuerySet evaluation and…


Checking how many queries reduce using these methods with an example

Photo by Etienne Boulanger on Unsplash

In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects.

I basically tried to figure out how and how many queries it reduces and, in this article, I will describe my findings.

You can find the source code on GitHub.

Throughout the article, we will be using the following models:

To test our function, we need to insert data into our models.

I wrote a management command for this reason which inserts five publishers, 100 books (20 books for each publisher) and 10 stores (10 books in each…


Understanding lambda, map, filter, reduce with examples.

lambda

A lambda is a small anonymous function which can take any number of arguments, but can only have one expression(not statements) and it returns a function object which can be assigned to any variable.

Basic syntax

lambda arguments : expression

Example

add = lambda x, y: x + y
print(add(2, 3))

Output :

5

map

The map() functions takes a function object and iterables like sequence, collection or an iterator object.You can send as many iterables as you like, just make sure the function has one parameter for each iterable. …


Writing a singleton decorator to use with any class

Photo by Patrick Schneider on Unsplash

Generally, we create many objects of classes according to our needs. Sometimes, creating multiple objects can be resource-intensive.

A real-world example can be the database connection class. You wouldn’t want to have multiple database objects because changes in one may make others inconsistent.

In these type of situations, we can use the singleton pattern. Using a singleton pattern, we ensure that a class creates only one instance.

There are several singletons in Python that you use frequently, including None, True, and False. …


A brief description of decorators in Python with an easy example

Photo by Shahadat Rahman on Unsplash

Functions

In Python, functions are the first-class objects, which means that:

  • Functions are objects — they can be referenced to, passed to a variable and returned from other functions as well.
  • Functions can be defined inside another function — an inner function — and can also be passed as an argument to another function.
def say_name():
print("Guido van Rossum")


def say_nationality():
print("Netherlands")


def say(func):
return func


say(say_name)()
say(say_nationality)()

Output:

Guido van Rossum
Netherlands

Here we are sending two different function references (not parentheses) to say function as an argument that returns the reference again.

This is how inner function works:

def…


Write less, do more

Photo by Austin Neill on Unsplash

Occurrence Counter in List

from collections import Counternum_lst = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3]
cnt = Counter(num_lst)
print(dict(cnt))
# first 2 most occurrence
print(dict(cnt.most_common(2)))
str_lst = ['blue', 'red', 'green', 'blue', 'red', 'red', 'green']
print(dict(Counter(str_lst)))

Output:

{1: 3, 2: 4, 3: 4, 4: 2, 5: 1}
{2: 4, 3: 4}
{'blue': 2, 'red': 3, 'green': 2}

Powerful One-Liner

salary = 4000

if salary > 9000:
tax = 900
elif 3000 < salary < 9000:
tax = 100
else:
tax = 0

print(f"Tax to pay : ${tax}")

tax = 900 if salary > 9000…


Deep dive into QuerySet’s evaluation and caching with examples

Photo by Christopher Gower on Unsplash

A QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the QuerySet.

Throughout the article we’ll refer to the following models:

from django.db import models

class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()

def __str__(self):
return self.name

class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
body_text = models.TextField(blank=True)

class Meta:
default_related_name = 'entries'

def __str__(self):
return self.headline

Take a look at following example to understand laziness :

q1 = Entry.objects.filter(blog=2)
q2 = q1.filter(headline__contains='food')
entry_list = list(q3)

Though this looks like two database…


Understanding Django life cycle.

Request-Response life cycle in Django

While setting up the django application in the server we need a webserver and a wsgi server. Webserver helps us in serving static files/content. If we did not use the webserver to serve static files then it has to served by WSGI server which results in more number of requests to the server. So, gradually it slow down the application performance. Web server balances the requests load on the server. We can divide request resources in two types.

1. static resource

2. dynamic resource(It has to process the data based on request to provide resource)

If browser request for the…

Goutom Roy

Engineer, son, brother, friend, archaeology enthusiast and history maniac.

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