dgplug member blogs


Read the latest posts from dgplug member blogs.

from pradhvan

In the last blog I talked about Iterators and Iterables and I am assuming you're familiar with both of the concepts. So moving forward from let's talk about generators.

Simply put generators are iterators with a yield keyword and they do not return they yield. Similarly, a generator function is one that has a yield keyword in its body.

Let's look at some code and find out a bit more about them so we can define them more formally.

def range_123():
    yield 1
    yield 2
    yield 3

for number in range_123():

numbers = range_123() # Assigning generator object to numbers

next(numbers) #Output -> 1
next(numbers) #Output -> 2
next(numbers) #Output -> 3
next(numbers) #Output -> StopIteration Error

When we look closely into the above code range_123() is a generator function. Since generators are iterator we can directly iterate over the whole iterator function or we could assign it to a generator object and then use the next keyword to iterate over it until it's exhausted and raises the StopIteration error in a manner of confirming with the IteratorPrortocal.

Now you must be wondering what is the difference between the yield and return?

  • When a return statement is invoked inside a function, it permanently passes control back to the caller of the function and disposes of a function's local state.

  • When a yield is invoked, it also passes the control back to the caller of the function but it only does so temporarily. It suspends the function and retains its local state.

def greeter(name):
    while True:
        yield f'Hello {name}'

gen_object = greeter('Pradhvan') 
next(gen_object) # Output -> Hello Pradhvan
next(gen_object) # Output -> Hello Pradhvan
next(gen_object) # Output -> Hello Pradhvan
next(gen_object) # Output -> Hello Pradhvan

If we look at the above code we could clearly see that local variable are stashed away temporaily, suspending the function and giving control back to the caller while retaining it's local state.

Since it's doing a lazy evaluation it can be continued anytime with the next() on the generator, which can evaluate somewhat infinitely long series of greeting messages.

Let's look at one more example of a code snippet where multiple yield statements decide the flow of the function.

def repeater():
    while True:
        yield 1
        yield 2
gen_obj = repeater()
next(iterator) # 1
next(iterator) # 2
next(iterator) # 3


The above example makes it clear that in a generator function the flow of control of where the function suspends is decided by the yield statement. As the #2 suspends the value at 2 and when we do next() on 3 we get the whole block of statements.

Generator Expression

A generator function can be replaced with a generator expression. These are similar to list comprehensions which that eagerly builds a list, generator expressions return a generator that can lazily produce the items.

def range_123():
    yield 1
    yield 3

res1 = [x*3 for x in range_123()]

Output res1:

for i in res1:
--> 3
--> 9
  • The list comprehension eagerly iterates over the items that are to be yielded and prints the Start Middle and End.
  • When the for is iterated over the list produced by the res1, it returns the item that are to be yielded.
def range_123():
    yield 1
    yield 3

res2 = (x*3 for x in range_123())

print(res2) # <generator object <genexpr> at 0x7f8be1d09150>

for i in res2:
  • In the case of generator expression, when the for loop iterates over the generator object res2, the body of the generator function range_123() actually executes.
  • Each iteration calls the next() while the iteration advances till a StopIteration is raised.

Since comprehension is a great way to increase the readability of your code and if you're using generator expression, you're making the comprehension more memory efficient.

But sometimes we tend to overuse the whole comprehension feature which backfires, I found a great article Overusing list comprehensions and generator expressions in Python which you should definitely look into.


from mrinalraj

Learning Unix commands are very essential as it helps you to navigate easily in your directories and files. Today we will learn some basics Unix commands which is easy for any beginners to begin with. Also you will get to know some bonus tips in the end.

Let's begin with creating new file.

cat > filename : creates a new file, if files already exists then overwrites it.

cat >> filename: appends the content in the already existing filename, else if not found then creates a new one.

Now to see if file is created or not.

ls -li : long list the files present in that directory with the inode no.

Now if you want to list files which is in some other directory or same working directory then there comes the concept of Relative addressing and Absolute addressing.

Relative addressing and absolute addressing

Relative addressing: here we can move to the directory which is under that directory.

username@hostname directoryname$ cd directory_name

Absolute Addressing: here we specify address from the root username@hostname directoryname$ cd /home/username/directory_name

Lets play with calendar commands.

cal: prints the calendar of current month

cal mm yyyy : will print calendar of that year of that month.

cal year : will print the calendar of that year

In Unix, you can do calculations as well.

bc: It will open binary calculator. Here you can perform calculations.

ln filename linkname : it creates a new link pointing to the existing file “file_name”

where cp filename newfilename : creates a new file with “newfilename” and then copies the content of the filename into it.

Note ls -li will confirm that in the copy command there will be different inode number while link command creates a new link to file as they have the same inode no.

mkdir is used to make a directory and rmdir is to remove a directory

rm file_name: is used to remove a file_name

Till now we learned some basic tips. Time for some Bonus Tips.

passwd : this command is used to change the current password

sudo passwd -l username : to lock that username from the system

sudo passwd -u username: to unlock that username from the system

sudo passwd -e username: to expire the username password next time he logins he has to give new passwd

sudo passwd -d username: deletes the password of that account and sets that account passwordless.


from abhinits2046

I was thinking to note down my thoughts so that I can share my experience. So here it is, about how I joined 'dgplug' and get to know about Open-Source.

During my B.Tech 3rd semester somehow I got to know about the word 'Open-Source'. After a year when I was a fifth semester student, I met 'Ratnadeep(rtnpro)' in a tech-talk at my college,talk was over Open-Source , Its opportunities and freedom.Open Source culture was a myth in my college, very few people knew about Open-Source and its freedom of learning. In my batch, hardly fifty percent people know about Open-Source and Communities. During the talk 'Ratnadeep debnath(rtnpro)' mentioned about 'dgplug' summer training program and also told about 'Kushal das(kushal)' and other 'dgplug' operators, in those days I was learning python so after the talk a name was coming again and again in my mind that was 'Kushal das(kushal)', there were many questions and doubts were in my mind e.g. how to start, where to start then I decided to ping 'Ratnadeep debnath(rtnpro)' and he helped me a lot. I was a hindi background student till my 12th standard so I was a little bit shy to talk ans also I was a window user in those days then 'Ratnadeep debnath(rtnpro)' suggested me to shift over fedora, and also suggest to join IRC to get enrolled in 'dgplug' where masterminds like Kushal, Ratnadeep(rtnpro), Sayan, Chandan , Jasonbraganza were there. Summer training program had been started 15 days before i joined. 'Kushal das' suggested me to go through the logs, I did that. Kushal das(kushal) provided his book for python named 'Python you and me', book helped me a lot to understand python with a decent practice. https://pymbook.readthedocs.io/en/latest/ I started digging more about Open-Source and i got my interests in it. At the beginning, after trying on my own, I lost hope because I was struggling to learn to contribute and thought that it's impossible ,I started staying on 'dgplug' after sessions and listened to people what they are taking and used to ask questions frequently whenever doubt appeared in my mind as time passed thing became easier, it's just start for me many thing to go. Jasonbraganza's sessions over reading and writing importance was amazing and encouraged me and many more to write, I am very much thankful to him for his kind help. That's how it all started for me.


from mrinalraj

In recent years, we have been in so much love for the free commodity without realizing we ourselves have become the commodity. We install only free apps from stores. This is to make you aware of the possible threat to our Right to Privacy which is very important:

What the problem is?

We have used Facebook like various free social networking sites which claims connecting people. Have you ever wondered how these proprietary companies are offering users its product for free? Yes, Facebook gets lots of revenue from adds. But how these adds are unknowingly so accurate? There has to be something tracking our data. These trackers know very effectively which sites have I visited and which product I looked in the cart. There has been many cases of phone tapping and call records that itself has put the citizens privacy a question.

Whom will our data benefit?

You might have gone through various surveys that asks you varieties of question and it will predict your personality. You fill it and submit ignoring the Terms and Condition. These can give them permissions to our personal data likes messages our locations etc. Now these contents are connected to my profile. Giving the direct access to any buyer about my pulse. These companies can now target the user by bombarding with the polarised content which is designed for me and seen only by me.

Why us?

We spent most of our time on these social sites liking and disliking the contents, called as data points . These data points can describe our personality. Through these personality they target those user whose decision can be influenced. These data are so much important to the buyer's that they can pay any amount. Most of the buyers are the political parities who want to influence the election by targeting its citizens. This is cheating democratic process of election. There is a instance during the Trump's Election campaign where a candidate named Ted Cruz won the election on the basis of the user's Facebook like. See how big that difference can cause. Data mining companies like Cambridge analytica had major role in his winning. According to the report Cambridge Analytica has stated that it has around 5000 data points of around millions of American's citizens.

Our privacy is our responsibility

We have to skeptic about our data sharing. You don't know how can some companies mines your data and influence you in their reasoning. Our society has to be updated with the current threat and unethical business model. As the world is getting more advanced keeping our data secure and private is very challenging. There have been many cases of data phishing and fraud calls where we unknowing share our personal and crucial details. The reason behind this is lack of awareness among the people. It is our duty to find the solution so that the technologies we build for human life enhancement should not break it.


from jason’s wotw blog

wotw, intersex

basically means that we finally admit to ourselves that we humans come in all shapes and sizes and that we cannot really slot or categorise people into our narrow worldview and then judge them for not meeting our crazy expectations.


from pradhvan

Iteration is the fundamental technique which is supported by every programming language in the form of loops. The most common one at least from is the For loop and if specifically talk about Python's case, we have For each loop. For each loop are powered by iterators. An iterator is an object that does the actual iterating and fetches data one at a time and on-demand.

Let's take a step back and look back at some of the common terms which would help us in understanding iterators even better.

iterables: anything that can be iterated over is called an iterable.

for item in some_iterable:

sequences: Sequences are iterables which can be indexed.

numbers = [1,2,3,4]
tuples = (1,2,3)
word = 'Hello world'

The iter function

Iter is built-in function and whenever the interpreter needs to iterator over an object, it automatically calls the iter().

The iter() function returns an iterator.

When the iter function is called it does three things:

  1. Checks whether the object implements __iter__ method. (To see this just do dir() on the object.)
  2. If the __iter__ method is not present but the __getitem__is implemented, python creates an iterator that fetches the items in order, starting from the index zero.
  3. If that fails a TypeError is raised stating “ Object is not iterable”.
numbers = [1,2,3,4]
num = iter(numbers) # Builds an iterator 'num' 

Looking at the code snippet above we can make a better definition of an iterable.

*Any object which the __iter__ built-in function can be called an iterable.*

Before moving forward let's look at nifty little way the iter() works with functions to make them work as an iterator.

Let's build a die roller that rolls a die from 1-6 and stops when the die hits 1.

In this usage we need to make sure of two things:

  1. That the iter function must receive a callable that will be invoked every time the next function is called and the callable function should not have any arguments.
  2. The second argument which is called the sentinel which acts as a flag will cause the iterator to raise an exception instead of returning the second argument.
def die_roll():
    return randint(1,6)

roller = iter(die_roll, 1)

print(type(roller)) # <class 'callable_iterator'>

for roll in roller:


Iterable vs Iterator

Python obtains an iterator from an iterable. Let's look at the for-each loop again to see how everything fits in the picture.

numbers = [1,2,3,4]
for number in numbers:

Looking at the code above we can only see the iterable i.e numbers. But what about the iterator? What about the iter() ? Isn't it suppose to use both to work.

Here we can't see the iterator or the iter() in action but it's working behind the scene. Let's re-write the whole statement in a while loop so we can see how it all fits together.

numbers = [1,2,3,4]
num = iter(numbers) # builds an iterator
while True:
    except StopIteration:
        del num

The flow of the above code is simple:

  1. Iterator num is created from the iterable.
  2. To obtain the value from the iterator next is used.
  3. Iterator raises the StopIteratioin error when there are no further items left.
  4. We delete the iterator and break out of the loop.

You must be wondering everything is fine but why did we delete the iterator.

Iterators have this property that they are one-directional and once all the item is iterated over they can't be reset to the original state.

Thus the StopIteration signals that the iterator is exhausted. Thus it's best to delete it.

Writing your own iterator

Python iterator objects are required to support two methods __iter__ and the __next__ method.

iter method returns self. This allows iterators to be used where an iterable is expected i.e “for” and “in” keywords.

next method returns the next available item, raising the StopIteration when there are no more items to be looped through.

Let's bundle this knowledge and build our very own Range built-in function.

class _Range:
    def __init__(self, start, end, step = 1):
        self.start = start
        self.end = end - 1 
        self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        if self.start > self.end:
            raise StopIteration
            self.start += self.step
            return self.start - 1

numbers = _Range(1, 3)
print(next(numbers)) # Result -> 1
print(next(numbers)) # Result -> 2
print(next(numbers)) # Raise a StopIteration Exception

Now that we know how an iterator works let's look back at the definition of an iterator again:

*Any object that implements the __next__ no-argument method that returns the next item in a series or raises StopIteration when there are no more items is called an Iterator.*

Just a quick tip before moving forward, the optimal way of creating your own iterator is to make a generator function, not by creating a iterator class like we did here.

Iterator Protocol

The iterator objects are required to support the following two methods, which together form the iterator protocol. The __iter__ and the __next__ method.

  • Iterator Protocol powers the all the iteration in python.
  • Iterator Protocol also powers the tuple unpacking in Python.
# Tuple unpacking
x,y,z = coordinates
  • Iterator Protocol also powers the star expressions.
numbers = [1,2,3,4,5]
a,b,*rest = numbers 
  • Most of the built-in functions that require some kind of looping(iterations) in python uses the Iterator Protocol.

Python's tongue twister

Iteratorables are not necessarily iterators but an iterator is necessarily iterable.

Example: Generators are iterators that can be looped over but lists are iterables but not an iterator.

Reasons to use Iterator:

  • Iterators allow lazy evaluation possible which saves memory.
  • Iterators allow for infinitely long iterables.

Not so common iterators

  • Enumerate objects are also iterators.
  • Zip objects are also iterators.
  • Reversed objects are iterators.
  • Files are also iterators.
letters = ['a','b','c','d']
next(enumerate(letters)) # Result -> (0, 'a')
next(zip(letters,letters)) #  Result -> ('a','a')
next(reversed(letters)) #  Result -> 'd'
next(open('iterator.txt')) #  Result -> 'iterator\n'

from nileshpatra

I have been using git from quite some time, but there are certain amazing things about git that I learnt just recently.

1. Blaming with git blame

git blame gives the commit hash, author and time for every line in a file. This can be used to know who are the people who have contributed to that particular code and the commit hash too! It can also help figure out who added a particular line in a project which broke it, and then go blame them :P

2. Rectifying via git commit —amend

Ever been in a hurry and made a spelling mistake? That's exactly what is command is for! This can change the commit message for the last commit. Just type git commit --amend that would open the file in the default terminal text editor. Change the message, save and quit, and done!

3. Squashing

Squash is not a command, but definitely a concept in itself. Imagine having changes in a file multiple times, which would make a lot of unnecessary commits. Now if any point of time, one needs to go back in history, doing that would be just plain painful with several commits cluttered. Squashing here comes to rescue! Squashing means convert related commits to one commit. It's nothing but a kind of interactive rebase. for last n commits you can do git rebase -i HEAD~n. Here's how it goes: squash1

This will open the commits in the default text editor. Instead of pick in front of commit, type squash for those commits you wish to squash.


Save and exit, you will get another file which asks the user to choose final commit messages. Type the appropriate message and delete other messages. Save an quit, it's squashed! \o/

4. Stashing

While working on projects, things are in a messy state and you want to switch branches for a bit to work on something else. Now, you do not want to commit things half done(you need to commit everything before switching). git stash comes to rescue! Stashing takes the current state of your working directory and pushes it onto a stack of unfinished changes. Now you can switch branches! You can also apply the unfinished changes any time with git stash apply

5. Tagging

Tagging is a feature in git. For every software there are releases, now imagine if a software is released and development team is working for the next release. Meanwhile, there is a bug report with severe priority. Now, hat needs to be fixed in the previous version! Remembering the last commit for each release is not a good idea. Git here offers the functionality! It has the ability to tag specific points in a repository’s history as being important(releases). There are five basic commands:

  • git tag – will list all the tags in the project.
  • git checkout <tag_version> – jumps to the repository's state with the particular tag version.
  • git tag -a <version> -m '<commit message> – creates a tag with the version number and commit message.
  • git tag -d <tag_name> – deletes the tag from the list
  • 'git push origin —tags` – pushes tags to the origin

6. Applying patches

A lot of open source work is done via mailing list. The kernel mailing list comes at the top of my head. A lot of commits are mailed as patches. These patches contain the diffs(git diff). They can be easily applied via git apply <filename>. Now the code can be tested with the patch applied.

7. Short git status

Git has a short status flag so you can see your changes in a more compact way. If you run git status -s or git status –short you get a more simplified output from the command. status-short The ?? indicates the file hasn't been staged. D indicates deleted file and there are a few other tags too.

8. Cloning can be done under a different name

You don't need to have a weird name that the upstream would have to your repository. You can always rename the directory while cloning. The syntax is: git clone <upstream URL> <directory name>

Git is indeed a wonderful tool in itself. There's so much to learn. Hope you enjoyed reading the blog, :)


from mrinalraj


Got a dream contributing to FOSS projects but lacking confidence in git commands. Don't worry this blog is for you: Let's begin learning git with the following FAQ:

  1. What is git init and why it's used?

    git init: Using this command we first initialize a local git repository. The files we will add here will now be tracked by the git. Running git init command is safe it reinitialize if there is an existing one.

  2. What is git clone and how can I clone a project?

    git clone https://github.com/your_username/repo_name: Will clone the remote repository into a newly-created directory.

  3. What's the status in git?

    git status: This command gives the list of files that have not been committed. This includes modified files and newly created files.

  4. What is Staging? How can I add a file to staging?

    Staging is like a checkpoint where only those files are there which is to be committed. Here we do modify any changes before final commit. git add [file-name.txt]: This command adds the file-name.txt to the staging area.

  5. How can I add all files to the staging area?

    git add -A or git add .: Using this command we can add all new and changed files to the staging area.* Note: There are times when unwanted files like file_name.swp also get added and committed to avoid this it's better to add files one by one.*

  6. How to commit a change with a proper message?

    git commit -m "[commit message]" -m is used to allow adding a commit message
    Using this command we can move all the staging area files to commit area in the local repository.

  7. How can I delete a file or folder?

    git rm file-name or git rm -r folder-name The above command are useful when you are deleting a file or deleting multiple files. git rm -r file-name removes the duplicate file-name recursively.

  8. I have created multiple branches. How can I get all my branches?

    git branch: This command lists all the branches created in your local repository. The asterisk denotes the current branch. git branch -a: This will list all the branches in the local as well as a remote repository.

  9. How to create and delete a branch?

    git branch [branch name]: This command will create a new branch.Note this does not checkout the new branch. git branch -d [branch name]: This command will delete the branch. This is the safest way to delete a branch as it prevents deletion if there are any unmerged changes. git branch -D [branch name]: This command will forcefully delete the branch and also deletes the commits associated with the branch. *Note all the above will bring changes in the local repository.

  10. How can I delete a branch in a remote repository?

    git push origin --delete [branch name]: This command will delete a remote branch.

  11. Can I create a new branch and automatically switch to it?

    Yes, you can use git checkout -b [branch name] command to create a branch and switch to that branch automatically.

  12. How to change branch present in a remote repository?

    Well, It depends on the Git version you are using. For modern version of git: git checkout [remotebranch] For older version of git : git checkout [remotebranch] origin/[remotebranch]

  13. What are the ways to see my commits?

    • git log: Using this we will see all the changes committed in the repositories.

    • git log --summary: Using this we get the detailed view of the changes made in the repositories.

    • git log --oneline: This command gives the history of the commits in brief.

  14. What are the ways to discard changes made to the file?

    • git checkout -- [file-name.txt]: This command will permanently discard all the changes made in the branch local repository.

    • git stash: This command will remove the changes made in the current branch but saves it for later use. So using git stash pop we can get back the saved changes made in the file of that branch.


from nileshpatra

Ever wondered to get a GUI application from another machine get rendered onto yours? If not, Linux offers that to you :P Let's see how: First of all we shall discus some basic terminologies before moving ahead:

The display server

The display server is very similar to a web-server. So Imagine that you have an apache server. Now when a client requests a service, the server would send a few instructions accordingly to the client over http/https protocol. The client(which here is the web browser) will render those instructions and display the content requested. The display server in Linux works almost the same way. The server here interacts with the hardware (CPU) and sends instructions over a protocol known as the 'X' protocol. The latest version of the same is 11, and hence it's called X11.


Think what would happen if the display-server is on one machine and client on the other machine? Yes! that would render the graphical applications onto the client machine. That's is exactly what X-forwarding is – render the application on one machine while it runs on a different machine.

Okay, enough of terminologies, let's get to implementing it now.

On the server, configure /etc/ssh/sshd_config to contain the following:

X11Forwarding yes
X11DisplayOffset 10

These two are usually commented out, ensure that the sshd_config contains these. You may need to restart ssh for the changes to be picked up. You can run this if the ssh server doesn't pick that up and then restart the server:

cat /var/run/sshd.pid | xargs kill -1

Next, start ssh on both the machines. On Debian or Debian derivatives you can do so by doing:

sudo service ssh start

Now we will connect the client to the server. On the client machine type:

ssh -X <server name>@<server ip>

If you are facing trouble finding out ip, you can do so via:

nmcli -p device show

And it's done! You have SSH'd into the server machine. Now you can render GUI apps on the client machine, while it runs on the server.


Here's me rendering firefox on the client :D


from mrinalraj

First of all kudos for successfully creating `.onion' address. If not, see my previous blog. Tor Browser

Just having a domain is useless if you don't know how to make use of it. So let's begin with the newly created domain. Note the following guidelines are verified on Ubuntu 18.04

Step 1 : First make a directory :-

sudo mkdir /var/www/your_directory_name cd /var/www/your_directory_name/

Step 2 : Create a file name index.html :-

touch index.html

Step 3 : Editing the newly created file

sudo vi index.html : sudo gives the power to override the readonly files Press 'i' to go in INSERT mode Write your good name Press ESC and give :wq as command to save index.html and exit vi Editor.

Step 4 : Editing the root :

cd /etc/nginx/sites-available/ : If says permission denied sudo it :) sudo vi default : It will open long content. Edit the root line from '/var/www/html' to '/var/www/yourdirectoryname'. Save and exit.

Step 5 : Reloading nginx :

systemctl reload nginx

Kudos our work is done

Step 6 : Open your domain name in Tor Browser :

Incase you forgot your domain name. Type sudo cat /var/lib/tor/hidden_service/hostname

Happy Coding :)


from pradhvan

Context Managers in Python help the users to manage the resources efficiently in a program i.e opening or closing a resource or locking or unlocking a resource. Context Managers come handy when we have to manage resource before and after an event.

The most common context manager that every python programmer uses very frequently for managing files, is a with as statement.

with open('MyContextManager.txt') as f:
    f.write('Using Context Manager is FUN !')

The above code snippet has mainly two advantages:

  • Helps to close resources automatically and effectively. This is a small code block, so it could be observed easily that the file was opened and closed properly but what would when the scope of the function increases? This is where context managers really come into the picture.
  • Makes the code readable and complex logic simple. The above code can also be written as:
file = open('MyContextManager.txt','W')
    file.write('Not using a Context Manager.')

Here we manage the opening and closing of a file manually with a try-finally statement.

Python's standard library comes with a module, contextlib. This contains utilities for working with context managers and the with statement.

Writing Your Own Context Manager

So why would someone want to write their own Context Managers?

Because, Context Managers are best at managing resources before and after an event; thus one doesn't have to worry about the allocation/de-allocation or Locking/Unlocking or Opening/Closing of events.

Also, they make the code simple and more readable.

Writing your own context manager can be done in two ways; either create your own class or use the Contextlib module to create a Context Manager decorator.

Let's first look at how we can create a simple Context Manager class. A Context Manager class consists of two main methods enter and exit. If you're familiar with testing, you can compare these two methods with the setup and teardown.

Just like every class in Python, the init method is optional. But in the case of Context Managers, we use init only if we're using a with as statement. init has to be passed the name which you want to associate with as in the with as statement.

Now let's take a look at a simple Game of Thrones inspired ContextManager which creates a dict of the house symbols.

class ThronesContextManager:
    def __init__(self, HouseSymbol):
        self.HouseSymbol = HouseSymbol

    def __enter__(self):
        print("Enter: {}".format(self.HouseSymbol)")
        return self.HouseSymbol

    def __exit__(self, *exc):
        print("Exit: {}".format(self.HouseSymbol))

with ThronesContextManager({"House Stark": "Wolf"}) as HouseSymbol:
    HouseSymbol["Targaryen"] = "Three Headed Dragon"
Enter: {'House Stark': 'Wolf'}
Exit: {'House Stark': 'Wolf', 'Targaryen': 'Three Headed Dragon'}
  • The init method takes in the dict associated with the as, similar to as what is done in the with-as statement. It creates an instance of the class and assigns it to the dict. Much similar to any normal Python Class.
  • The enter method is called by the with and is passed the dict. It returns the value which is associated with the dict(HouseSymbol).
  • The exit takes in the exception(*exc), these are of mainly three types exc: exception, exctype: exception type and exctb: exception_traceback.
  • If for some reason you want the program to ignore the exception you can also return True to just ignore the exception.

Now taking a look at the above code example we can say that any Context Manager has two methods an enter method and an exit method.

Before moving forward to contextmanager decorator let's break down the code snippet we saw in the starting of the post and see how it works behind the hood.

Since we know how context managers work it won't be difficult to the observe what's happening when we call with as statement while opening a file.

with open('MyContextManager.txt') as f:
    f.write('Using Context Manager is FUN !')
  1. With calls the enter method of the File class.
  2. The enter method opens the file and returns it.
  3. The opened file handle is passed to f.
  4. We write to the file using .write().
  5. The with statement calls the exit method.
  6. The exit checks for exceptions, if no exception is found it closes the file.

The easier way to write a context manager is by using the Contextlib module and creating a context manager decorator.

The good thing about using the @contextmanager is that it builds the enter and exit method for you automatically, thus we can transform a generator function into a contextmanager decorator.

Let's re-write the ThronesContextManager again but with a @ThronesContextManager.

from contextlib import contextmanager

def ThronesContextManager(data):
    print("Enter: {}".format(data))
    yield data 
    print("Exit: {}".format(data))

with ThronesContextManager({"House Stark": "Wolf"}) as HouseSymbol:
    HouseSymbol["House Targaryen"] = "Three Headed Dragon"
Enter: {'House Stark': 'Wolf'}
Exit: {'House Stark': 'Wolf', 'House Targaryen': 'Three Headed Dragon'}


Here are some interesting things I found about Contextmanagers. I came across these while researching for this blog post and hence the that's the reason I am adding this to the section PyRandom. I would keep updating this section as I learn more about Context Managers.

  • Context Managers do not create a separate new scope in the program i.e variables defined inside the withas block will be available after the block is executed.
with open('MyContextManager.txt') as f:
    # Variable defined inside the Context Manager
    VariableName = f.read()
  • When using multiple ContextManager in a withas statement the flow of enter and exit statement becomes LIFO(Last In First Out) i.e the enter method that is called last will have it's exit method called first.
import contextlib

def make_context(name):
    print ('entering:', name)
    yield name
    print ('exiting :', name)

with make_context('A') as A, make_context('B') as B, make_context('C') as C:
    print ('inside with statement:', A, B, C)
entering: A
entering: B
entering: C
inside with statement: A B C
exiting : C
exiting : B
exiting : A

What now ?

Since we covered all the basic stuff on Context Managers, we can start digging deeper and learn to use Context Managers in a more realistic scenarios. So here are a few things that I would like you to read more about:

  • Learn how to handle exceptions in/with Context Managers.
  • Try to find out real project use cases where using a Context Manager would be best suited.
  • Find out the role of init and enter in the Context Manager.

Still can't get enough ?

The reason behind the blog is that I recently picked a Python problem which goes something like this

Write a Context Manager named Suppress which suppresses the exception of a given type/types i.e if the given exception type is raised, that exception should be caught and muted in a sense.

Code Example:

>>> x = 0
>>> with suppress(ValueError):
...     x = int('hello')
>>> x
>>> with suppress(ValueError, TypeError):
...     x = int(None)
>>> x

Since you read this far I am assuming you are also just starting to learn about this topic. Let's put it all that we have learned so far to a test and get some hands-on experience of writing your Context Manager. Try to solve this problem.

I am still solving the problem and once it's done I would link my solution here.

Happy Coding !


from mrinalraj

Onion Note : The following guidelines are verified on Ubuntu 18.04 First install tor and nginx using the following commands: sudo apt install tor sudo apt install nginx sudo ufw allow Nginx Full

Open Terminal and enter : vi /etc/tor/torrc command press i to go in INSERT mode. then search for ############### This section is just for location-hidden services ###

Un-comment the following 2 lines by removing “#” symbol. HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 80

to exit vi press Esc then enter :wq to save the changes and exit.

Try to restart the tor and nginx services by the following two commands: sudo service tor restart sudo systemctl restart nginx

On entering the command : sudo ls /var/lib/tor/hidden_service/ you will find filename such as hostname and private key. Enter : sudo cat /var/lib/tor/hidden_service/hostname use will find .onion address. Check it on the Tor browser.

“Congrats you got your own new domain.”

This post may contain error. Please bring it to the notice to help others. By connecting Mrinal Raj


from ritik5049

Nowdays these two types of encryption methods are widely used. * Symmetric encryption * Asymmetric encryption

Symmetric Encryption

In symmetric encryption single key is used by both sender and receiver for encryption and decryption. Therefore both the parties have to exchange the key and thus trust issues arise here a lot. Some of symmetric key algorithms are DES(Data Encryption Standard), Triple DES, AES(Advanced Encryption Standard).


Suppose there are two-person A and B, A wants to send his/her data from an insecure network to B. A will encrypt the data with key and B will have to decrypt it with the same key.

Asymmetric Encryption

In asymmetric encryption pair of the key are used, one is called public key and the other is private key. The private key is kept secret by the owner and the public key is shared. Data encrypted with the recipient's public key can only be decrypted by the corresponding private key.


Suppose A wants to send data to B, so A must have B's public key to encrypt the data then B decrypt the same with his/her corresponding private key.


from ritik5049

Hey everyone if you want to view information about CPU in Linux you can use the command cat /proc/cpuinfo in terminal it will display what type of processor your system is running and the number of CPUs present and much more. Here is an example. cpuinfo


from ritik5049

Hello folks, my self Ritik Raushan. This is my first blog ever written by me. I`ll be going to publish much more technical kinds of stuff in upcoming posts. Here we will learn and grow together. See you again.