How to fix “unindent does not match any outer indentation level” indentation error in Python

Fix unindent does not match any outer indentation level

Python is an emerging language in the developer field. It’s great as first language because it’s concise, easy to read, fast enough for most tasks and has a large ecosystem which fits mostly everything from web development to scientific programming.

Back then when I was new to Python, one of the thing that frustrates me the most was IndentationError: unindent does not match any outer indentation level. Look at how it made people pull their hair out :

Fixing this error is easy, and should be easy, but to understand why it happens so that you can write clean, concise, maintainable code requires more reading.

What “unindent does not match any outer indentation level” means?

Just like the error message says, there could be something wrong with the spaces and tabs indentation in your code.

Along with the IndentationError provided, the terminal should give you the exact line the error is occuring on. Using that piece of information, you could look closely into where the problem arised.

What causes “unindent does not match any outer indentation level” in Python

There are a number of reasons for this error to happen. This is an exaustive list of main causes, sorted by popularity :

  1. You are mixing tabs and spaces in your code. There might be a few spaces mixed in with your tabs, or vice versa. If you are using a text editor, you can manually doing a search and replace with tabs and spaces. However, using a source-code editor or a full-fledged IDE is a better idea since they have automatic correction built-in.
  2. You may have placed a few extra spaces or tabs here and there. For example, you could have put 5 spaces where it should be 4 spaces at the beginning of a line.
  3. You forgot to indent compound statements, which could be any ‘if’, ‘for’, ‘while’ etc.
  4. User-defined functions/classes was not indented properly.

Manually fix IndentationError

If you are using some kind of primitive editors like Notepad or Gedit, you should try doing an exhaustive search and replace like this

  • Press Ctrl + H to open Find and Replace, then replace any tab with exactly 4 spaces
  • Find and Replace again, this time replace exactly 5 spaces with 4 spaces to remove any extra spaces left in the code.
  • Your code should run without errors by now, but if it doesn’t, I highly suggest switching to another editor. My recommendation is Visual Studio Code.

Format your code properly to avoid “unindent does not match any outer indentation level”

Solution 1 : Using Visual Studio Code

First, you need to have Visual Code Studio installed

Open your source code in Visual Studio Code, then press one of these shortcuts to run Code Formatting:

  • Visual Studio Code on Windows – Shift + Alt + F
  • Visual Studio Code on MacOS – Shift + Option + F
  • Visual Studio Code on Ubuntu – Ctrl + Shift + I

Even better, you can also edit the preferences to enable Visual Studio Code‘s automatic code formatting right before saving any .py files. To do that, open File → Preferences → Workspace Settings (or alternatively press Ctrl + , ) and add all the config below to workspace settings:

{ "editor.formatOnSave": true }

Note : to properly format your code with all the recommendations in PEP 8 — Style Guide for Python Code, you should install autopep8, which fixes numerous styling problems. I personally got rid of IndentationError messages since I used it. Also, automatic code linting with flake8 or pylint is something a professional developer can’t live without, so check it out if you want to level up your game a little bit.

Solution 2 : Using Python’s IDLE

For those of you who don’t know what IDLE is, IDLE stands for Integrated Development Environment, and it’s bundled in all versions of Python.

Python’s IDLE have its own way of fixing this, just follow the steps below, if it suggests one similar message:

  1. Choose All, e.g. Ctrl + A
  2. Select Format → Untabify Region
  3. Double check if your indenting is still correct, then save and rerun the program.

Solution 3 : Using Atom

For Atom users, follow these steps to reformat the code:

  1. Go to Packages.
  2. Choose Whitespace.
  3. Convert Spaces to Tabs.
  4. Check your file indentation.

How to fix locale.Error: unsupported locale setting in Python

Fix Python locale.error

Python is a popular general purpose programming language that can be used to serve many different use cases. Created by Guido van Rossum with the name inspired from British comedy show Monty Python, it was set out to be straightforward and easy-to-use, emphasized in wp-block-code readability. Python 3 is the latest version of the language and is considered to be the future of Python.

The set up of Python 3 on your Linux machine should be straightforward without any error, but sometimes you will encounter locale.Error: unsupported locale setting – one of the most common problem of Python. This tutorial will show you how to fix it explicitly on Ubuntu 18.04, but the process remains the same for other distro.

When does locale.Error happens?

The root cause is: your environment variable LC_ALL is missing or invalid somehow

➜ ~ pip install virtualenv Traceback (most recent call last): File "/usr/bin/pip", line 11, in <module> sys.exit(main()) File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main locale.setlocale(locale.LC_ALL, '') File "/usr/lib64/python3.4/locale.py", line 592, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting

locale.Error could be triggered when you :

  • Using pip to install a package that make use of locale package on a newly installed machine
  • Using virtualenv to make a new virtual environment
  • You’ve been fiddling with the environment variables then try to use pip
  • Running programs built with Python for the first time after fresh OS installation.
  • Sometimes it happens with programs like ssh, a2enmod, and perl programs too.

How to fix locale.Error quickly?

If you want to solve it quick, you can sequentially run the commands below in the terminal :

export LC_ALL="en_US.UTF-8" export LC_CTYPE="en_US.UTF-8" sudo dpkg-reconfigure locales

The first two commands set the LC_ALL and LC_CTYPE environment variables, then the third one commits the changes to the system. After running these, a few command-line style window could probably pop up, you can just hit OK until it’s done, there is pretty much nothing to configure.

Here is a one-liner for you the lazy guys :

export LC_ALL="en_US.UTF-8" & export LC_CTYPE="en_US.UTF-8" & sudo dpkg-reconfigure locales

The output should look like this :

~$ export LC_ALL="en_US.UTF-8" & export LC_CTYPE="en_US.UTF-8" & sudo dpkg-reconfigure locales [1] 7201 [2] 7202 [sudo] password for user: Generating locales (this might take a while)... en_AG.UTF-8... done en_AU.UTF-8... done en_BW.UTF-8... done en_CA.UTF-8... done en_DK.UTF-8... done en_GB.UTF-8... done en_HK.UTF-8... done en_IE.UTF-8... done en_IL.UTF-8... done en_IN.UTF-8... done en_NG.UTF-8... done en_NZ.UTF-8... done en_PH.UTF-8... done en_SG.UTF-8... done en_US.UTF-8... done en_ZA.UTF-8... done en_ZM.UTF-8... done en_ZW.UTF-8... done vi_VN.UTF-8... done Generation complete. [1]- Done export LC_ALL="en_US.UTF-8" [2]+ Done export LC_CTYPE="en_US.UTF-8"

Fix locale.Error permanently

While you can set the locale exporting an environment variable, you will have to do that every time you start a session, meaning after a restart, things would go back the same as before. Setting a locale the following way will solve the problem permanently.

First, you need to install locales package :

sudo apt-get install locales -y

Then use the locale-gen command to generate locales :

sudo locale-gen en_US.UTF-8

After that, permanently set the configuration to the system

sudo echo "LANG=en_US.UTF-8" > /etc/default/locale

You might also need to restart your system for changes to take effect.

Fix locale.Error for Docker

Just add these lines to your Dockerfile

Dockerfile# Set the locale RUN locale-gen en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US.UTF-8

After setting the locale, verify that the system is updated by using the following command :

~$ locale LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL=en_US.UTF-8

How to install pip on Ubuntu 18.04 the official way

Installing pip on Ubuntu 18.04 the official way

pip is the standard, de-facto package installer for Python. Created to be a better alternative to easy_install, It enables you to install and manage additional packages from PyPI that are not part of the standard Python library. This tutorial will show you the official, recommended way to install pip for both Python 2 and Python 3 on Ubuntu 18.04 LTS and how they will coexist peacefully.

Why do I need to care about pip for Python2 and pip for Python 3?

As the Python community grows, more and more parts of Ubuntu switched to the language. Because of that, Python 2 is now a part of the standard installation of Ubuntu. Despite the fact that Python 3 has many advantages over Python 2, the latter remains a crucial depency of the system. Removing Python 2.7 from Ubuntu 18.04 can cause a lot of trouble in the long run.

Ubuntu 18.04 ships with both Python 2 and Python 3 preinstalled. One pip installation works with only one Python distribution, so we need to separate both the command to invoke pip and the installation itself. For example, pip, by default, calls pip-for-python2 and pip3 is equivalent to pip-for-python3.

Installing pip3 and pip from Ubuntu Repository

Start off by updating system repository using the following command : 

sudo apt update

Then using the following command to install pip for Python 3 (refered to as pip3) and pip for Python 2 (pip) as well as all their depencies.

sudo apt install python3-pip python-pip -y

One the installation is completed, check and verify that pip and pip3 installs successfully using the following command : 

pip3 --version

pip number version may vary depending on the current updated repo, but it should look like this : 

pip 19.0.3 from /usr/local/lib/python3.6/dist-packages/pip (python 3.6)

Similarly, pip version can be verified using the command below : 

pip 19.0.3 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)

Installing pip independently using official install script

While the installation method above is fast and easy, there is another official method using the script provided by pip development team.

First you need to verify that your system doesn’t have any existing pip installation.

pip --version Command 'pip' not found. Try: sudo apt install <deb name>

Then download the installation script by running

wget https://bootstrap.pypa.io/get-pip.py

Proceed by using the python version of your choice to run the script. Be cautious as the script doesn’t coordinate well with the preinstalled pip version and can cause conflict if you have get-pip.py installed over the preinstalled one.

For example, the command for installing pip for Python 3 system-wide would be 

sudo python3 get-pip.py

If you want to install pip for Python 3 for the current user, run

python3 get-pip.py --user

Similarly, the command for pip-on-Python2 should be

sudo python get-pip.py OR python get-pip.py --user

Basic pip usage

Installing a package with pip

pip is made to manage the installation of third-party packages, one of the functionality is installing packages via the following command.

pip install <package_name>

Uninstalling a package

If you don’t need the package anymore you can uninstall it easily with the following command

pip uninstall <package_name>

Searching for Libraries

One can fire up the browser and search for a package on PyPI official website, but you can also do that using command line. For our example let’s look for packages related to “requests“. The search command shows us an extensive list similar to the one below.

pip search requests requests-hawk (1.0.0) - requests-hawk requests-dump (0.1.3) - `requests-dump` provides hook functions for requests. pydantic-requests (0.1.1) - A pydantic integration with requests. requests-foauth (0.1.1) - Requests TransportAdapter for foauth.org! requests-auth (4.0.1) - Easy Authentication for Requests Requests-OpenTracing (0.0.1) - OpenTracing support for Requests yamlsettings-requests (1.0.0) - YamlSettings Request Extension requests-aws4auth (0.9) - AWS4 authentication for Requests requests-middleware (0.1.2) - Composable HTTP middleware for requests jupyter-requests (0.0.2) - Send requests to a Jupyter server. requests-twisted (0.1.2) - Twisted adapter for the requests library. requests-oauthlib (1.2.0) - OAuthlib authentication support for Requests. requests-ftp (0.3.1) - FTP Transport Adapter for Requests. requests-async (0.5.0) - async-await support for `requests`. requests-cache (0.5.0) - Persistent cache for requests library requests-circuit (0.1.0) - A circuit breaker for Python requests requestor-requests (0.1.0) - Requestor Helper to request package requests-core (0.0.0) - A minimal HTTP Client, for Requests. .........and many more.................

Batch installing depencies

Python codes distributed online often includes requirements.txt file declaring all the depencies. If you see this file, you can run this command to install all depencies instead of manually run pip install for each depency.

pip install -r requirements.txt

Show what files are installed and its paths

Sometimes you want to analyze a package’s code, then this command will help you locate its files.

pip show --files OnePackage Name: OnePackage Version: 1.0 Location: /my/env/lib/pythonx.x/site-packages Files: ../OnePackage/__init__.py [...]

Conclusion

Now you should have a basic understanding on how to install pip on your Ubuntu 18.04 and how to manage Python packages using pip. For more information, visit the pip user guide page.

How to install rclone on Ubuntu 18.04

Install Rclone on Ubutu 18.04

In this article, we are going to learn about a powerful command-line tool to sync files and directories to and from different cloud storage providers.

Dubbed “rsync for cloud storage”the open-source rclone enables you to send data back and forth to the likes of Google Drive, OneDrive, Amazon S3, Yandex Disk, etc.

rclone comes with a few useful features:

  • Always checks for file integrity using MD5/SHA-1 hashes
  • Timestamps preserved on files uploaded
  • Partial syncs supported on a whole file basis
  • Built-in Copy mode to just copy new/changed files
  • Sync (one way) mode to make a directory identical
  • Check mode to check for file hash equality
  • Can sync to and from network, e.g. syncing two different cloud accounts
  • Optional encryption (Crypt), optional cache (Cache), optional FUSE mount (rclone mount)
  • Multi-threaded downloads to local storage
  • Supports HTTP/WebDav/FTP/SFTP/DLNA

How to install rclone on Ubuntu

Because rclone is written in Go programing language, it comes in a single binary file.

There are several ways to install it on Ubuntu. The easiest approach would be to use official package for apt or the snap package manager. Alternatively, you can install rclone using a bash install script provided by its development team.

We will walk you through all of them in this article.

Install rclone the official package from Ubuntu repositories (for Ubuntu 18.04 onwards).

Since Ubuntu 18.04 Bionic Beaver, rclone has become mature enough to become a part of the official repositories. To most users, this is the best way as you will have the most stable, well-tested version of rclone on your system.
If the package manager of your choice is apt, simply run these commands in your terminal. We’ll first make sure that the system is fully updated.

sudo apt update && sudo apt upgrade sudo apt install rclone -y

Unfortunately, if you prefer snap app store, I have bad news for you : rclone development team has abandoned support for the snap package because it’s too hard to make it work properly (and peacefully) with the security confinement of snap.

Install rclone using the official bash script

If you have any problem with the package provided by Ubuntu (which is quite rare by the way), you can always install rclone using an official bash script from the development team. Open up your terminal and run the following commands :

You have to make sure curl is installed on your system :

curl --version

If you see something like this, then you’re good to go:

curl 7.58.0 (x86_64-pc-linux-gnu) libcurl/7.58.0 OpenSSL/1.1.0g zlib/1.2.11 libidn2/2.0.4 libpsl/0.19.1 (+libidn2/2.0.4) nghttp2/1.30.0 librtmp/2.3 Release-Date: 2018-01-24 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smb smbs smtp smtps telnet tftp Features: AsynchDNS IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy PSL

If you see something like this, you will need to install curl first :

Command 'curl' not found, did you mean: command 'curl' from deb curl Try: sudo apt install

Get curl to your system :

sudo apt install curl -y

Download the bash script and let it does the install :

curl https://rclone.org/install.sh | sudo bash

If you have any difficulties in installing rclone using any of the methods above, please dont hesitate, let me know in the comments below.