DEV Community

Cover image for 6 Python Built-in Modules You Need To Know About
Mithil Poojary
Mithil Poojary

Posted on

6 Python Built-in Modules You Need To Know About

1. Convert Python2 code to Python3 with 2to3

How many times did you turn down a python script just because it was written in Python2? 2to3 converts Python2 code to Python3.

2to3 -w example.py
Enter fullscreen mode Exit fullscreen mode
Before | After

Alt Text

2. Create an HTTP server with http.server

Place your index.html file and start a local webserver.
In the same directory as the index file, run:

python3 -m http.server 8000
Enter fullscreen mode Exit fullscreen mode

Now you can visit localhost:8000.

3. Pretty Print JSON using json.tool

I like to deal with most of my developer things inside the terminal, as it is generally faster to implement. Ever had to deal with JSON in your terminal? You must have if you used curl before.

curl -s https://dev.to/api/articles\?username=mithil467
Enter fullscreen mode Exit fullscreen mode

Alt Text

The output is not pretty printed and it's impossible to make anything out of the result. Python's json.tool has got your back!

curl -s https://api.github.com/users/Mithil467 | python -m json.tool
Enter fullscreen mode Exit fullscreen mode

Alt Text
I further piped the output to pygmentize -l javascript for better visual impact.

4. Better text wrapping with textwrap

Back then when I was developing Mitype, I had this exact problem. I had to do text wrapping based on the width of the terminal.
I ended up writing my algorithm, but now I have found this!

S = "I have started my journey into blogging! Can I call myself a writer now?"
S_wrapped = textwrap.fill(S, width=14)

I have started
my journey
into blogging!
Can I call
myself a
writer now?
Enter fullscreen mode Exit fullscreen mode

5. Print tokens for your code with tokenize

Tokenizing is a stage in the compilation phase where source code elements are converted into tokens. Let's tokenize the same file that we used in our 2to3 example.

python3 -m tokenize app.py
Enter fullscreen mode Exit fullscreen mode

Alt Text
You might want to have a look at some more builtin modules here https://docs.python.org/3/py-modindex.html

| Cover pic by Chris Ried on Unsplash

Top comments (0)