__future__  module with unicode_literals function

In Python2.x we can not use Unicode but future modules allow us to use Unicode.

Example 1: 

In Python2 strings are considered bytes strings but in later versions, all strings are considered as a Unicode string.

Python




# code in Python2
print(type("Geeks"))


Output:

<type 'str'>

Let use the future module in Python2.

Python




# code in Python2
from __future__ import unicode_literals
  
print(type("Geeks"))


Output:

<type 'unicode'>

Example 2:

let’s see the example without future module, it will raise an error because we are building a byte string that holds UTF-8 encoded bytes

Python




# encoding: utf-8
name = 'helló wörld from example'
print name.encode('utf8')


Output:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print name.encode('utf8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)

And it can be done in Python2X with future modules.

Python




# encoding: utf-8
from __future__ import unicode_literals
name = 'helló wörld from example'
print name.encode('utf8')


Output:

helló wörld from example


__future__ Module in Python

__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. 

This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module. Its releases are in Python version 2.1. The basic idea of the __future__ module is to help migrate to use Python 3.X features. 

Note: The future statements must at the top of the file, otherwise the Python interpreter will raise SyntaxError

Similar Reads

Following features in this module:

Features Optional in Mandatory in nested_scopes 2.1 2.2 generators 2.2 2.3 division 2.2 3.0 absolute_import 2.5 3.0 with_statement 2.5 2.6 print_function 2.6 3.0 unicode_literals 2.6 3.0 generator_stop 3.5 3.7 annotations 3.7 3.11...

__future__ module with print_function

...

__future__  module with division function

Example 1:...

__future__  module with unicode_literals function

...