Python Equivalent to Java Final Keyword

Hello, fellow developers! Today in this tutorial, we will learn the Python equivalent to Java’s ‘final’ keyword.

Introduction to Final Keyword in Java

In Java, the final keyword is used to declare and work with constants. As the name suggests, the variable gets one final value and becomes immutable (unchangeable). They are useful when the developer wants to preserve the integrity and safety of the data being used.

Python Equivalent to Java Final Keyword

In Python, there isn’t a direct implementation of the final keyword but yes there are some alternative workarounds. We will be covering the following approaches in this tutorial:

  1. Approach 1: Using Python Constants
  2. Approach 2: Using Immutable Data Types in Python
  3. Approach 3: Using Python Decorators

Approach 1: Using Python Constants

In Python, we can create constants by convention (Uppercase names) that the developer technically shouldn’t reassign. This is a simple method that makes constants distinguishable from the non-constant variables. But as this method only relies on convention, if the developer doesn’t follow proper discipline then this approach can be of no use as well.

CODESPEEDY_CONSTANT = 10

Approach 2: Using Immutable Data Types in Python

To enforce immutability in Python codes, we can make use of immutable data types in Python like tuples and frozen sets. This will ensure that the developer can’t change the values even by mistake.

Also Read: What are the Mutable and Immutable objects in Python?

However, the problem with this approach is that the in-built data types might not be suitable for all situations and can end up making things even more complex rather than making it simpler.

codespeedy_tuple = (1, 2, 3)
codespeedy_frozenset = frozenset([4, 5, 6])

Approach 3: Using Python Decorators

A developer can make use of decorators and wrap a class under them to enforce immutability and avoid any further changes in the functions/classes. A major advantage to this approach is that decorators can be customized to perform as close to the final keyword functionality as possible. However, they do add a level of complexity to the coding approach and can also result in unexpected errors or exceptions.

Also Read: Use of Decorators in Python

def finalKeywordDecorator(func):
    def wrapper(*args, **kwargs):
        raise TypeError("Cannot modify as this is a final function")
    return wrapper

@finalKeywordDecorator
def codespeedyFinalFunction():
    return "This function mimics final keyword"

Now if we ever try to change/modify the value of this codespeedyFinalFunction function we will end up with the following exception:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-fa33988fa5d1> in <cell line: 10>()
      8     return "This function mimics final keyword"
      9 
---> 10 codespeedyFinalFunction()

<ipython-input-5-fa33988fa5d1> in wrapper(*args, **kwargs)
      1 def finalKeywordDecorator(func):
      2     def wrapper(*args, **kwargs):
----> 3         raise TypeError("Cannot modify as this is a final function")
      4     return wrapper
      5 

TypeError: Cannot modify as this is a final function

I hope you learned something new through this tutorial. If you liked this tutorial, have a look at the tutorials below as well:

  1. List of all Keywords in Python
  2. Check if a string is a keyword or not in Python
  3. How to Type Hint Enum in Python

Happy Learning!

Leave a Reply

Your email address will not be published. Required fields are marked *