Tuesday, February 7, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Python

Improve Your Code’s Maintainability – Real Python

learningcode_x1mckf by learningcode_x1mckf
September 7, 2022
in Python
0
Improve Your Code’s Maintainability – Real Python
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


In programming, the time period fixed refers to names representing values that don’t change throughout a program’s execution. Constants are a elementary idea in programming, and Python builders use them in lots of instances. Nevertheless, Python doesn’t have a devoted syntax for outlining constants. In follow, Python constants are simply variables that by no means change.

To forestall programmers from reassigning a reputation that’s supposed to carry a relentless, the Python neighborhood has adopted a naming conference: use uppercase letters. For each Pythonista, it’s important to know what constants are, in addition to why and when to make use of them.

On this tutorial, you’ll discover ways to:

  • Correctly outline constants in Python
  • Determine some built-in constants
  • Use constants to enhance your code’s readability, reusability, and maintainability
  • Apply totally different approaches to manage and handle constants in a mission
  • Use a number of methods to make constants strictly fixed in Python

By studying to outline and use constants, you’ll dramatically enhance your code’s readability, maintainability, and reusability.

To be taught essentially the most from this tutorial, you’ll want primary information of Python variables, functions, modules, packages, and namespaces. You’ll additionally have to know the fundamentals of object-oriented programming in Python.

Understanding Constants and Variables

Variables and constants are two historic and elementary ideas in pc programming. Most programming languages use these ideas to govern information and work in an efficient and logical trend.

Variables and constants will in all probability be current in every mission, app, library, or different piece of code that you simply’ll ever write. The query is: what are variables and constants in follow?

What Variables Are

In math, a variable is outlined as a logo that refers to a price or amount that can change over time. In programming, a variable can also be a logo or title usually related to a reminiscence handle containing a price, object, or piece of information. Like in math, the content material of a programming variable can change in the course of the execution of the code that defines it.

Variables usually have a descriptive title that’s someway related to a goal worth or object. This goal worth might be of any information sort. So, you should use variables to signify numbers, strings, sequences, customized objects, and extra.

You possibly can carry out two essential operations on a variable:

  1. Entry its worth
  2. Assign it a brand new worth

In most programming languages, you possibly can entry the worth related to a variable by citing the variable’s title in your code. To assign a brand new worth to a given variable, you’ll use an assignment assertion, which frequently consists of the variable’s title, an task operator, and the specified worth.

In follow, you’ll discover many examples of magnitudes, information, and objects that you would be able to signify as variables. A couple of examples embrace temperature, velocity, time, and size. Different examples of information that you would be able to deal with as variables embrace the variety of registered customers in a web app, the variety of lively characters in a video game, and the variety of miles coated by a runner.

What Constants Are

Math additionally has the idea of constants. The time period refers to a price or amount that by no means modifications. In programming, constants consult with names related to values that by no means change throughout a program’s execution.

Similar to variables, programming constants include two issues: a reputation and an related worth. The title will clearly describe what the fixed is all about. The worth is the concrete expression of the fixed itself.

Like with variables, the worth related to a given fixed might be of any of information sort. So, you possibly can outline integer constants, floating-point constants, character constants, string constants, and extra.

After you’ve outlined a relentless, it’ll solely assist you to carry out a single operation on it. You possibly can solely entry the fixed’s worth however not change it over time. That is totally different from a variable, which lets you entry its worth, but in addition reassign it.

You’ll use constants to signify values that received’t change. You’ll discover numerous these values in your day-to-day programming. A couple of examples embrace the velocity of sunshine, the variety of minutes in an hour, and the title of a mission’s root folder.

Why Use Constants

In most programming languages, constants shield you from unintentionally altering their values someplace within the code if you’re coding at two within the morning, inflicting surprising and hard-to-debug errors. Constants additionally make it easier to make your code extra readable and maintainable.

Some benefits of utilizing constants as an alternative of utilizing their values instantly in your code embrace:

Benefit Description
Improved readability A descriptive title representing a given worth all through a program is at all times extra readable and express than the bare-bones worth itself. For instance, it’s simpler to learn and perceive a relentless named MAX_SPEED than the concrete velocity worth itself.
Clear communication of intent Most individuals will assume that 3.14 could consult with the Pi fixed. Nevertheless, utilizing the Pi, pi, or PI title will talk your intent extra clearly than utilizing the worth instantly. This follow will enable different builders to grasp your code shortly and precisely.
Higher maintainability Constants allow you to make use of the identical title to establish the identical worth all through your code. If it’s essential to replace the fixed’s worth, then you definitely don’t have to alter each occasion of the worth. You simply have to alter the worth in a single place: the fixed definition. This improves your code’s maintainability.
Decrease threat of errors A continuing representing a given worth all through a program is much less error-prone than a number of express situations of the worth. Say that you simply use totally different precision ranges for Pi relying in your goal calculations. You’ve explicitly used the values with the required precision for each calculation. If it’s essential to change the precision in a set of calculations, then changing the values might be error-prone as a result of you possibly can find yourself altering the mistaken values. It’s safer to create totally different constants for various precision ranges and alter the code in a single place.
Lowered debugging wants Constants will stay unchanged throughout this system’s lifetime. As a result of they’ll at all times have the identical worth, they shouldn’t trigger errors and bugs. This characteristic is probably not crucial in small initiatives, however it might be essential in massive initiatives with a number of builders. Builders received’t have to take a position time debugging the present worth of any fixed.
Thread-safe information storage Constants can solely be accessed, not written. This characteristic makes them thread-safe objects, which signifies that a number of threads can concurrently use a relentless with out the chance of corrupting or shedding the underlying information.

As you’ve discovered on this desk, constants are an vital idea in programming for good purpose. They will make your life extra nice and your code extra dependable, maintainable, and readable. Now, when do you have to use constants?

When Use Constants

Life, and significantly science, is stuffed with examples of fixed values, or values that by no means change. A couple of examples embrace:

  • 3.141592653589793: A continuing denoted by π, spelled as Pi in English, which represents the ratio of a circle’s circumference to its diameter
  • 2.718281828459045: A continuing denoted by e and often known as Euler’s number, which is intently associated to the natural logarithm and compound interest
  • 3,600: The variety of seconds in a single hour, which is taken into account fixed in most functions, although leap seconds typically are added to account for variability within the Earth’s rotation velocity
  • -273.15: A continuing representing absolute zero in levels Celsius, which is the same as 0 kelvins on the Kelvin temperature scale

All of the above examples are fixed values that individuals generally use in life and science. In programming, you’ll typically end up coping with these and plenty of different comparable values that you would be able to think about and deal with as constants.

In abstract, use a relentless to signify a amount, magnitude, object, parameter, or another piece of information that’s supposed to stay unchanged throughout its lifetime.

Defining Your Personal Constants in Python

Up up to now, you’ve discovered about constants as a normal idea in life, science, and programming. Now it’s time to find out how Python offers with constants. First, you need to know that Python doesn’t have a devoted syntax for outlining constants.

In different phrases, Python doesn’t have constants within the strict sense of the phrase. It solely has variables, primarily due to its dynamic nature. Due to this fact, to have a relentless in Python, it’s essential to outline a variable that by no means modifications and persist with that conduct by avoiding task operations on the variable itself.

Notice: On this part, you’ll give attention to defining your personal constants. Nevertheless, there are a couple of constants which can be constructed into Python. You’ll study them later on.

Then, how would Python builders know {that a} given variable represents a relentless? The Python neighborhood has determined to make use of a robust naming conference to tell apart between variables and constants. Preserve studying to be taught extra!

Person-Outlined Constants

To inform different programmers {that a} given worth must be handled as a relentless, you need to use a extensively accepted naming conference for the fixed’s identifier or title. It’s best to write the title in capital letters with underscores separating phrases, as said within the Constants part of PEP 8.

Listed below are a couple of instance of user-defined Python constants:

PI = 3.14
MAX_SPEED = 300
DEFAULT_COLOR = "33[1;34m"
WIDTH = 20
API_TOKEN = "593086396372"
BASE_URL = "https://api.example.com"
DEFAULT_TIMEOUT = 5
ALLOWED_BUILTINS = ("sum", "max", "min", "abs")
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    ...
]

Notice that you simply’ve created these constants precisely as you’d create variables. You’ve used a descriptive title, the task operator (=), and the fixed’s particular worth.

By utilizing capital letters solely, you’re speaking that the present title is meant to be handled as a relentless—or extra exactly, as a variable that by no means modifications. So, different Python builders will know that and hopefully received’t carry out any task operation on the variable at hand.

Notice: Once more, Python doesn’t help constants or non-reassignable names. Utilizing uppercase letters is only a conference, and it doesn’t stop builders from assigning new values to your fixed. So, any programmer working in your code must be cautious and by no means write code that modifications the values of constants. Keep in mind this rule since you additionally have to comply with it.

As a result of Python constants are simply variables, each comply with comparable naming guidelines, with the one distinction being that constants use uppercase letters solely. Following this concept, constants’ names can:

  • Be of any size
  • Include uppercase letters (A–Z)
  • Embody digits (0–9) however not as their first character
  • Use underscore characters (_) to separate phrases or as their first character

Utilizing uppercase letters makes your constants stand out out of your variables. This fashion, different builders will unambiguously acknowledge their goal.

As a normal naming advice, keep away from abbreviated names when defining constants. The aim of a relentless’s title is to make clear the which means of the fixed’s worth to be able to reuse it later. This objective calls for descriptive names. Keep away from utilizing single-letter names, unusual abbreviations, and generic names like NUMBER or MAGNITUDE.

The really helpful follow is to outline constants on the prime of any .py file proper after any import statements. This fashion, folks studying your code will instantly know the constants’ goal and anticipated therapy.

Module-Degree Dunder Constants

Module-level dunder names are particular names that begin and finish with a double underscore. Some examples embrace names resembling __all__, __author__, and __version__. These names are usually handled as constants in Python initiatives.

Notice: In Python, a dunder title is a reputation with particular which means. It begins and ends in double underscores, and the phrase dunder is a portmanteau of double underneathrating.

Based on Python’s coding model information, PEP 8, module-level dunder names ought to seem after the module’s docstring and earlier than any import assertion aside from __future__ imports.

Right here’s a pattern module that features a bunch of dunder names:

# greeting.py

"""This module defines some module-level dunder names."""

from __future__ import barry_as_FLUFL

__all__ = ["greet"]
__author__ = "Actual Python"
__version__ = "0.1.0"

import sys

def greet(title="World"):
    print(f"Hey, title!")
    print(f"Greetings from model: __version__!")
    print(f"Yours, __author__!")

On this instance, __all__ defines up entrance the listing of names that Python will import if you use the from module import * import assemble in your code. On this case, somebody importing greeting with a wildcard import will simply get the greet() perform again. They received’t have entry to __author__, __version__, and different names not listed on __all__.

Notice: The from module import * assemble permits you to import all of the names outlined in a given module in a single go. The __all__ attribute restricts the imported names to solely these within the underlying listing.

The Python neighborhood strongly discourages this import assemble, generally often known as wildcard imports, as a result of it tends to litter your present namespace with names that you simply in all probability received’t use in your code.

In distinction, __author__ and __version__ have which means just for the code’s authors and customers quite than for the code’s logic itself. These names must be handled as constants since no code must be allowed to alter the writer or model throughout this system’s execution.

Notice that the greet() perform does entry the dunder names however doesn’t change them. Right here’s how greet() works in follow:

>>>

>>> from greeting import *

>>> greet()
Hey, World!
Greetings from model: 0.1.0!
Yours, Actual Python!

Typically, there are not any arduous guidelines that stop you from defining your personal module-level dunder names. Nevertheless, the Python documentation strongly warns towards utilizing dunder names apart from these usually accepted and utilized by the neighborhood. The core builders could introduce new dunder names to the language sooner or later with none warning.

Placing Constants Into Motion

Thus far, you’ve discovered about constants and their function and significance in programming. You’ve additionally discovered that Python doesn’t help strict constants. That’s why you possibly can consider constants as variables that by no means change.

Within the following sections, you’ll code examples of how beneficial constants might be in your day-to-day coding journey.

Changing Magic Numbers for Readability

In programming, the time period magic number refers to any quantity that seems instantly in your code with none rationalization. It’s a price that comes out of the blue, making your code enigmatic and obscure. Magic numbers additionally makes applications much less readable and tougher to keep up and replace.

For instance, say you’ve got the next perform:

def compute_net_salary(hours):
    return hours * 35 * (1 - (0.04 + 0.1))

Are you able to inform up entrance what the which means of every quantity on this computation is? Most likely not. The totally different numbers on this perform are magic numbers as a result of you possibly can’t reliably infer their meanings from the numbers themselves.

Try the next refactored model of this perform:

HOURLY_SALARY = 35
SOCIAL_SECURITY_TAX_RATE = 0.04
FEDERAL_TAX_RATE = 0.10

def compute_net_salary(hours):
    return (
        hours
        * HOURLY_SALARY
        * (1 - (SOCIAL_SECURITY_TAX_RATE + FEDERAL_TAX_RATE))
    )

With these minor updates, your perform now reads like a appeal. You and another builders studying your code can certainly inform what this perform does since you’ve changed the unique magic numbers with appropriately named constants. The title of every fixed clearly explains its corresponding which means.

Each time you end up utilizing a magic quantity, take the time to interchange it with a relentless. This fixed’s title have to be descriptive and unambiguously clarify the which means of the goal magic quantity. This follow will routinely enhance the readability of your code.

Reusing Objects for Maintainability

One other on a regular basis use case of constants is when you’ve got a given worth repeatedly showing in several elements of your code. In the event you insert the concrete worth into the code at each required place, then you definitely’ll be in bother if you happen to ever want to alter the worth for any purpose. On this scenario, you’ll want to alter the worth in each place.

Altering the goal worth in a number of locations at a time is error-prone. Even if you happen to depend on your editor’s Discover and Exchange characteristic, you possibly can depart some unchanged situations of the worth, which might result in surprising bugs and peculiar behaviors later.

To forestall these annoying points, you possibly can substitute the worth with a correctly named fixed. It will assist you to set the worth as soon as and repeat it in as many areas as wanted. In the event you ever want to alter the fixed’s worth, then you definitely simply have to alter it in a single place: the fixed definition.

For instance, say you’re writing a Circle class, and also you want strategies to compute the circle’s space, perimeter, and so forth. After a couple of coding minutes, you find yourself with the next class:

# circle.py

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def space(self):
        return 3.14 * self.radius**2

    def perimeter(self):
        return 2 * 3.14 * self.radius

    def projected_volume(self):
        return 4/3 * 3.14 * self.radius**3

    def __repr__(self):
        return f"self.__class__.__name__(radius=self.radius)"

This instance uncovers how the approximate worth of Pi (3.14) has been written as a magic quantity in a number of strategies of your Circle class. Why is that this follow an issue? Say it’s essential to enhance the precision of Pi. Then you definitely’ll need to manually change the worth in not less than three totally different locations, which is tedious and error-prone, making your code troublesome to keep up.

Notice: Typically, you don’t have to outline Pi your self. Python ships with some built-in constants, together with Pi. You’ll see the right way to benefit from it later.

Utilizing a named fixed to retailer the worth of Pi is a wonderful strategy to fixing these points. Right here’s an enhanced model of the above code:

# circle.py

PI = 3.14

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def space(self):
        return PI * self.radius**2

    def perimeter(self):
        return 2 * PI * self.radius

    def projected_volume(self):
        return 4/3 * PI * self.radius**3

    def __repr__(self):
        return f"self.__class__.__name__(radius=self.radius)"

This model of Circle makes use of the worldwide fixed PI to interchange the magic quantity. This code has a number of benefits in comparison with the unique code. If it’s essential to enhance the precision of Pi, then you definitely simply need to replace the PI fixed’s worth initially of the file. This replace will instantly replicate on the remainder of the code with out requiring any extra motion in your aspect.

Notice: Constants shouldn’t change throughout your code’s execution. Nevertheless, throughout improvement, you possibly can change and tweak your constants in response to your wants. Updating the precision of Pi in your Circle class is an efficient instance of why you could want to alter the worth of a relentless in the course of the improvement of your code.

One other benefit is that now your code is extra readable and simpler to grasp. The fixed’s title is self-explanatory and displays the accepted math terminology.

Declaring a relentless as soon as after which reusing it a number of occasions, as you probably did within the above instance, represents a big maintainability enchancment. In the event you ever need to replace the fixed’s worth, then you definitely’ll replace it a single place quite than in a number of locations, which means manner much less effort and error threat.

Offering Default Argument Values

Utilizing named constants to supply default argument values to capabilities, strategies, and lessons is one other widespread follow in Python. There are many examples of this follow within the Python standard library.

For instance, the zipfile module offers instruments to create, learn, write, append, and listing ZIP information. Essentially the most related class on this module is ZipFile. With ZipFile, you possibly can manipulate your ZIP information effectively and shortly.

The class constructor of ZipFile takes an argument known as compression, which lets you choose amongst a couple of obtainable information compression strategies. This argument is optional and has ZIP_STORED as its default worth, which means that ZipFile doesn’t compress the enter information by default.

On this instance, ZIP_STORED is a continuing outlined in zipfile. The fixed holds a numeric worth for uncompressed information. You’ll additionally discover different compression strategies represented by named constants like ZIP_DEFLATED for the Deflate compression algorithm, for instance.

The compression argument within the ZipFile class constructor is an efficient instance of utilizing constants to supply default argument values when you’ve got an argument that may take solely a restricted variety of legitimate values.

One other instance of when constants turn out to be useful as default argument values is when you’ve got a number of capabilities with a recurrent argument. Say that you simply’re growing an utility that connects to an area SQLite database. Your app makes use of the next set of capabilities to handle the database:

import sqlite3
from sqlite3 import Error

def create_database(db_path):
    # Code to create the preliminary database goes right here...

def create_connection(db_path):
    # Code to create a database connection goes right here...

def backup_database(db_path):
    # Code to again up the database goes right here...

These capabilities carry out totally different actions in your SQLite database. Notice that every one your capabilities share the db_path argument.

When you’re growing the applying, you determine to supply a default database path to your capabilities to be able to shortly take a look at them. On this case, you possibly can instantly use the trail as a default worth to the db_path argument.

Nevertheless, it’s higher to make use of a named fixed to supply the default database path:

import sqlite3
from sqlite3 import Error

DEFAULT_DB_PATH = "/path/to/database.sqlite"

def create_database(db_path=DEFAULT_DB_PATH):
    # Code to create the preliminary database goes right here...

def create_connection(db_path=DEFAULT_DB_PATH):
    # Code to create a database connection goes right here...

def backup_database(db_path=DEFAULT_DB_PATH):
    # Code to again up the database goes right here...

This small replace lets you shortly take a look at your app by concentrating on a pattern database throughout improvement. It additionally improves the maintainability of your code as a result of you possibly can reuse this fixed in different database-related capabilities that seem in future variations of your app.

Lastly, you’ll discover conditions by which you wish to cross an object with sure conduct to a category, technique, or perform. This follow is usually often known as duck typing and is a elementary precept in Python. Now say that your code will care for offering an ordinary implementation of the required object. In case your customers desire a customized object, then they need to present it themselves.

On this scenario, you should use a relentless to outline the default object after which cross this fixed as a default argument worth to the goal class, technique, or perform. Try the next instance of a hypothetical FileReader class:

# file_handler.py

from readers import DEFAULT_READER

class FileHandler:
    def __init__(self, file, reader=DEFAULT_READER):
        self._file = file
        self._reader = reader

    def learn(self):
        self._reader.learn(self._file)

    # FileHandler implementation goes right here...

This class offers a technique to manipulate several types of information. The .learn() technique makes use of the injected reader object to learn the enter file in response to its particular format.

Right here’s a toy implementation of a reader class:

# readers.py

class _DefaultReader:
    def learn(self, file):
        with open(file, mode="r", encoding="utf-8") as file_obj:
            for line in file_obj:
                print(line)

DEFAULT_READER = _DefaultReader()

The .learn() technique on this instance takes the trail to a file, opens it, and prints its content material to the display screen line by line. This class will play the function of your default reader. The ultimate step is to create a relentless, DEFAULT_READER, to retailer an occasion of your default reader. That’s it! You might have a category that processes the enter information and likewise a helper class that gives the default reader.

Your customers also can code customized readers. For instance, they will code readers for CSV and JSON information. As soon as they’ve written a given reader, they will cross it into the FileHandler class constructor and use the ensuing occasion to deal with information that use the reader’s goal file format.

Dealing with Your Constants in a Actual-World Challenge

Now that you understand how to create constants in Python, it’s time to discover ways to deal with and manage them in a real-world mission. You should utilize a number of approaches or methods to this finish. For instance, you possibly can put your constants in:

  • The identical file because the code that makes use of them
  • A devoted module for project-wide constants
  • A configuration file
  • Some atmosphere variables

Within the following sections, you’ll write some sensible examples that show the above methods for managing constants appropriately.

Placing Constants Collectively With Associated Code

The primary and perhaps most pure technique to prepare and handle your constants is to outline them along with the code that makes use of them. With this strategy, you’ll be defining the constants on the prime of the module that comprises the associated code.

For instance, say that you simply’re making a customized module to carry out calculations, and it’s essential to use math constants like Pi, Euler’s quantity, and some others. On this case, you are able to do one thing like this:

# calculations.py

"""This module implements customized calculations."""

# Imports go right here...
import numpy as np

# Constants go right here...
PI = 3.141592653589793
EULER_NUMBER = 2.718281828459045
TAU = 6.283185307179586

# Your customized calculations begin right here...
def circular_land_area(radius):
    return PI * radius**2

def future_value(present_value, interest_rate, years):
    return present_value * EULER_NUMBER ** (interest_rate * years)

# ...

On this instance, you outline your constants in the identical module the place the code utilizing them lives.

Notice: If you wish to explicitly talk {that a} fixed must be utilized in its containing module solely, then you possibly can add a number one underscore (_) to its title. For instance, you are able to do one thing like _PI = 3.141592653589793. This main underscore labels the title as non-public, which signifies that the consumer’s code shouldn’t use this title instantly.

Placing your constants along with the code that makes use of them is a fast and applicable technique for narrow-scope constants which can be solely related to a single module in a given mission. On this case, you in all probability received’t be utilizing the constants exterior the containing module itself.

Making a Devoted Module for Constants

One other widespread technique for organizing and managing your constants is making a devoted module by which to place all of them. This technique is suitable for constants which can be utilized in many modules and even packages throughout a given mission.

The central concept of this technique is to create an intuitive and distinctive namespace for constants. To use this technique to your calculations instance, you possibly can create a Python package deal containing the next information:

calc/
├── __init__.py
├── calculations.py
└── constants.py

The __init__.py file will flip the calc/ listing right into a Python package deal. Then you possibly can add the next content material to your constants.py file:

# constants.py

"""This module defines project-level constants."""

PI = 3.141592653589793
EULER_NUMBER = 2.718281828459045
TAU = 6.283185307179586

When you’ve added this code to constants.py, then you possibly can import the module every time it’s essential to use any of your constants:

# calculations.py

"""This module implements customized calculations."""

# Imports go right here...
import numpy as np

from . import constants

# Your customized calculations begin right here...
def circular_land_area(radius):
    return constants.PI * radius**2

def future_value(present_value, interest_rate, years):
    return present_value * constants.EULER_NUMBER ** (interest_rate * years)

# ...

Notice that you simply import the constants module instantly from the calc package deal utilizing a relative import. Then you definitely use absolutely certified names to entry any required constants in your calculations. This follow improves your communication of intent. Now it’s utterly clear that PI and EULER_NUMBER are constants in your mission due to the constants prefix.

To make use of your calculations module, you are able to do one thing like this:

>>>

>>> from calc import calculations
>>> calculations.circular_land_area(100)
31415.926535897932

>>> from calc.calculations import circular_land_area
>>> circular_land_area(100)
31415.926535897932

Now your calculations module lives contained in the calc package deal. Which means if you wish to use the capabilities in calculations, then it’s essential to import calculations from calc. You may as well import the capabilities instantly by referencing the package deal and the module such as you did within the second instance above.

Storing Constants in Configuration Recordsdata

Now say that you simply wish to go additional on the subject of externalizing the constants of a given mission. You could have to maintain all of your constants out of your mission’s supply code. To do that, you should use an exterior configuration file.

Right here’s an instance of the right way to transfer your constants to a configuration file:

; constants.ini

[CONSTANTS]
PI=3.141592653589793
EULER_NUMBER=2.718281828459045
TAU=6.283185307179586

This file makes use of the INI file format. You possibly can learn any such file utilizing the configparser module from the usual library.

Now get again to calculations.py and replace it to look one thing like the next:

# calculations.py

"""This module implements customized calculations."""

# Imports go right here...
from configparser import ConfigParser

import numpy as np

constants = ConfigParser()
constants.learn("path/to/constants.ini")

# Your customized calculations begin right here...
def circular_land_area(radius):
    return float(constants.get("CONSTANTS", "PI")) * radius**2

def future_value(present_value, interest_rate, years):
    return (
        present_value * float(constants.get(
            "CONSTANTS",
            "EULER_NUMBER"
        ))) ** (interest_rate * years)

# ...

On this instance, your code first reads the configuration file and shops the ensuing ConfigParser object in a worldwide variable, constants. You may as well title this variable CONSTANTS and use it globally as a relentless. Then you definitely replace your calculations to learn the constants from the configuration object itself.

Notice that ConfigParser objects retailer the configuration parameters as strings, so it’s essential to use the built-in float() perform to transform the values into numbers.

This technique could also be useful if you’re making a graphical user interface (GUI) app and have to set some parameters to outline the form and dimension of the app’s home windows when loading and exhibiting the GUI, for instance.

Dealing with Constants as Setting Variables

One other useful technique to deal with your constants is to outline them as system variables if you happen to’re on Home windows or atmosphere variables if you happen to’re on macOS or Linux.

This strategy is usually used to configure deployment in several environments. You may as well use atmosphere variables for constants that suggest safety dangers and shouldn’t be instantly dedicated to the supply code. Examples of a majority of these constants embrace authentication credentials, API entry tokens, and so forth.

Notice: It’s best to be careful when utilizing atmosphere variables for delicate info as a result of they could be unintentionally uncovered in logs or to baby processes. All cloud suppliers supply some form of secrets management that’s safer.

To make use of this technique, you first should export your constants as atmosphere or system variables in your working system. There are not less than two methods to do that:

  1. Manually export the constants in your present shell session
  2. Add your constants to the shell’s configuration file

The primary method is fairly fast and sensible. You should utilize it to run some quick exams in your code. For instance, say that it’s essential to export an API token as a system or atmosphere variable. In that case, you simply have to run the next command:

C:> set API_TOKEN="593086396372"
$ export API_TOKEN="593086396372"

The primary downside of this method is that your constants shall be accessible solely from the command-line session by which you outlined them. A a lot better strategy is to make your working system load the constants everytime you hearth up a command-line window.

In the event you’re on Home windows, then take a look at the Configuring Environment Variables part in Your Python Coding Environment on Windows: Setup Guide to discover ways to create system variables. Comply with the directions on this information and add an API_TOKEN system variable with a price of 593086396372.

In the event you’re on Linux or macOS, then you possibly can go to your private home folder and open your shell’s configuration file. When you’ve opened that file, add the next line on the finish of it:

# .bashrc

export API_TOKEN="593086396372"
# .zshrc

export API_TOKEN="593086396372"

Linux and macOS routinely load the corresponding shell configuration file everytime you begin a terminal or command-line window. This fashion, you make sure that the API_TOKEN variable is at all times obtainable in your system.

When you’ve outlined the required atmosphere variables on your Python fixed, then it’s essential to load them into your code. To do that, you should use the environ dictionary from Python’s os module. The keys and values of environ are strings representing the atmosphere variables and their values, respectively.

Your API_TOKEN fixed is now current within the environ dictionary. Due to this fact, you possibly can learn it from there with simply two strains of code:

>>>

>>> import os

>>> os.environ["API_TOKEN"]
'593086396372'

Utilizing atmosphere variables to retailer constants, and the os.environ dictionary to learn them into your code, is an efficient manner of configuring constants that depend upon the atmosphere your utility is deployed in. It’s significantly helpful when working with the cloud, so maintain this method in your Python device package.

Exploring Different Constants in Python

Aside from user-defined constants, Python additionally defines a number of inside names that may be thought-about as constants. A few of these names are strict constants, which means that you would be able to’t change them as soon as the interpreter is working. This the case for the __debug__ fixed, for instance.

Within the following sections, you’ll study some inside Python names that you would be able to think about and may deal with as constants in your code. To kick issues off, you’ll evaluate some built-in constants and fixed values.

Constructed-in Constants

Based on the Python documentation, “A small variety of constants reside within the built-in namespace” (Source). The primary two constants listed within the docs are True and False, that are the Python Boolean values. These two values are additionally situations of int. True has a price of 1, and False has a price of 0:

>>>

>>> True
True
>>> False
False

>>> isinstance(True, int)
True
>>> isinstance(False, int)
True

>>> int(True)
1
>>> int(False)
0

>>> True = 42
    ...
SyntaxError: can not assign to True

>>> True is True
True
>>> False is False
True

Notice that the True and False names are strict constants. In different phrases, they will’t be reassigned. In the event you attempt to reassign them, then you definitely get a SyntaxError. These two values are additionally singleton objects in Python, which means that there’s just one occasion of every. That’s why the identity operator (is) returns True within the ultimate examples above.

One other vital and commonplace fixed worth is None, which is the null worth in Python. This fixed worth is useful if you wish to specific the concept of nullability. Similar to True and False, None can also be a singleton and strict fixed object that may’t be reassigned:

>>>

>>> None is None
True

>>> None = 42
    ...
SyntaxError: can not assign to None

None is sort of helpful as a default argument worth in capabilities, strategies, and sophistication constructors. It’s usually used to speak {that a} variable is empty. Internally, Python makes use of None because the implicit return worth of capabilities that don’t have an explicit return statement.

The ellipsis literal (...) is one other fixed worth in Python. This particular worth is similar as Ellipsis and is the one occasion of the types.EllipsisType sort:

>>>

>>> Ellipsis
Ellipsis

>>> ...
Ellipsis

>>> ... is Ellipsis
True

You should utilize Ellipsis as a placeholder for unwritten code. You may as well use it to interchange the pass assertion. In sort hints, the ... literal communicates the concept of an unknown-length collection of information with a uniform sort:

>>>

>>> def do_something():
...     ...  # TODO: Implement this perform later
...

>>> class CustomException(Exception): ...
...
>>> increase CustomException("some error message")
Traceback (most up-to-date name final):
    ...
CustomException: some error message

>>> # A tuple of integer values
>>> numbers: tuple[int, ...]

The Ellipsis fixed worth can turn out to be useful in lots of conditions and make it easier to make your code extra readable due to its semantic equivalence to the English ellipsis punctuation signal (…).

One other fascinating and probably helpful built-in fixed is __debug__, as you already discovered initially of this part. Python’s __debug__ is a Boolean fixed that defaults to True. It’s a strict fixed as a result of you possibly can’t change its worth as soon as your interpreter is working:

>>>

>>> __debug__
True

>>> __debug__ = False
    ...
SyntaxError: can not assign to __debug__

The __debug__ fixed is intently associated to the assert assertion. Briefly, if __debug__ is True, then all of your assert statements will run. If __debug__ is False, then your assert statements shall be disabled and received’t run in any respect. This characteristic can barely enhance the efficiency of your manufacturing code.

Notice: Regardless that __debug__ additionally has a dunder title, it’s a strict fixed as a result of you possibly can’t change its worth as soon as the interpreter is working. In distinction, the inner dunder names within the part beneath must be handled as constants however aren’t strict constants. You possibly can change their values throughout your code’s execution. Nevertheless, this follow might be difficult and would require superior information.

To alter the worth of __debug__ to False, you need to run Python in optimized mode through the use of the -O or -OO command-line choices, which give two ranges of bytecode optimization. Each ranges generate an optimized Python bytecode that doesn’t comprise assertions.

Inner Dunder Names

Python additionally has a broad set of inside dunder names that you would be able to think about as constants. As a result of there are a number of of those particular names, you’ll simply study __name__ and __file__ on this tutorial.

Notice: To dive deeper into different dunder names in Python and what they imply to the language, take a look at the official documentation about Python’s data model.

The __name__ attribute is intently associated to the way you run a given piece of code. When importing a module, Python internally units __name__ to a string containing the title of the module that you simply’re importing.

Hearth up your code editor and create the next pattern module:

# sample_name.py

print(f"The kind of __name__ is: sort(__name__)")
print(f"The worth of __name__ is: __name__")

After getting this file in place, get again to your command-line window and run the next command:

$ python -c "import sample_name"
The kind of __name__ is: <class 'str'>
The worth of __name__ is: sample_name

With the -c swap, you possibly can execute a small piece of Python code on the command line. On this instance, you import the sample_name module, which prints some messages to the display screen. The primary message tells you that __name__ is of sort str, or string. The second message exhibits that __name__ was set to sample_name, which is the title of the module you simply imported.

Alternatively, if you happen to take sample_name.py and run it as a script, then Python will set __name__ to the "__main__" string . To verify this truth, go forward and run the next command:

$ python sample_name.py
The kind of __name__ is: <class 'str'>
The worth of __name__ is: __main__

Notice that now __name__ holds the "__main__" string. This conduct signifies that you simply’ve run the file instantly as an executable Python program.

The __file__ attribute will comprise the trail to the file that Python is at present importing or executing. You should utilize __file__ from inside a given module when it’s essential to get the trail to the module itself.

For instance of how __file__ works, go forward and create the next module:

# sample_file.py

print(f"The kind of __file__ is: sort(__file__)")
print(f"The worth of __file__ is: __file__")

In the event you import the sample_file module in your Python code, then __file__ will retailer the trail to its containing module in your file system. Verify this out by working the next command:

$ python -c "import sample_file"
The kind of __file__ is: <class 'str'>
The worth of __file__ is: /path/to/sample_file.py

Likewise, if you happen to run sample_file.py as a Python executable program, then you definitely get the identical output as earlier than:

You might also like

Build a Wordle Clone With Python and Rich – Real Python

Create Interactive Maps & Geospatial Data Visualizations With Python – The Real Python Podcast

Build a JavaScript Front End for a Flask API – Real Python

$ python sample_file.py
The kind of __file__ is: <class 'str'>
The worth of __file__ is: /path/to/sample_file.py

Briefly, Python units __file__ to comprise the trail to the module from which you’re utilizing or accessing this attribute.

Helpful String and Math Constants

You’ll discover many helpful constants in the usual library. A few of them are tightly linked to some particular modules, capabilities, and lessons. Others are extra generic, and you should use them in varied situations. That’s the case with some math and string-related constants that yow will discover within the math and string modules, respectively.

The math module offers the next constants:

>>>

>>> import math

>>> # Euler's quantity (e)
>>> math.e
2.718281828459045

>>> # Pi (π)
>>> math.pi
3.141592653589793

>>> # Infinite (∞)
>>> math.inf
inf

>>> # Not a quantity (NaN)
>>> math.nan
nan

>>> # Tau (τ)
>>> math.tau
6.283185307179586

These constants will turn out to be useful everytime you’re writing math-related code and even code that simply makes use of them to carry out particular computations, like your Circle class again within the Reusing Objects for Maintainability part.

Right here’s an up to date implementation of Circle utilizing math.pi as an alternative of your customized PI fixed:

# circle.py

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def space(self):
        return math.pi * self.radius**2

    def perimeter(self):
        return 2 * math.pi * self.radius

    def projected_volume(self):
        return 4/3 * math.pi * self.radius**3

    def __repr__(self):
        return f"self.__class__.__name__(radius=self.radius)"

This up to date model of Circle is extra readable than your authentic model as a result of it offers extra context on the place the Pi fixed comes from, making it clear that it’s a math-related fixed.

The math.pi fixed additionally has the benefit that if you happen to’re utilizing an older model of Python, then you definitely’ll get a 32-bit model of Pi. In distinction, if you happen to use Circle in a contemporary model of Python, then you definitely’ll get a 64-bit model of Pi. So, your program will self-adapt to its concrete execution atmosphere.

The string module additionally defines a number of helpful string constants. The desk beneath exhibits the title and worth of every fixed:

Identify Worth
ascii_lowercase abcdefghijklmnopqrstuvwxyz
ascii_uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ
ascii_letters ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
digits 0123456789
hexdigits 0123456789abcdefABCDEF
octdigits 01234567
punctuation !”#$%&'()*+,-./:;<=>[email protected][]^_`~
whitespace The mixture of the space character, horizontal and vertical tab, linefeed, carriage return, and form feed
printable The mixture of digits, ascii_letters, punctuation, and whitespace

These string-related constants turn out to be useful in lots of conditions. You should utilize them if you’re doing lots of string processing, working with regular expressions, processing natural language, and extra.

Sort-Annotating Constants

Since Python 3.8, the typing module features a Final class that permits you to type-annotate constants. In the event you use this class when defining your constants, then you definitely’ll inform static sort checkers like mypy that your constants shouldn’t be reassigned. This fashion, the kind checker can assist you detect unauthorized assignments in your constants.

Listed below are some examples of utilizing Remaining to outline your constants:

from typing import Remaining

MAX_SPEED: Remaining[int] = 300
DEFAULT_COLOR: Remaining[str] = "33[1;34m"
ALLOWED_BUILTINS: Final[tuple[str, ...]] = ("sum", "max", "min", "abs")

# Later in your code...
MAX_SPEED = 450  # Can not assign to ultimate title "MAX_SPEED" mypy(error)

The Remaining class represents a particular typing assemble that signifies sort checkers to report an error if the title at hand is reassigned in some unspecified time in the future in your code. Notice that although you get a kind checker’s error report, Python does change the worth of MAX_SPEED. So, Remaining doesn’t stop unintentional fixed reassignments at runtime.

Defining Strict Constants in Python

Up up to now, you’ve discovered quite a bit about programming and Python constants. You now know that Python doesn’t help strict constants. It simply has variables. Due to this fact, the Python neighborhood has adopted the naming conference of utilizing uppercase letters to speak {that a} given variable can be a fixed.

So, in Python, you don’t have constants. Moderately, you’ve got variables that by no means change. This may be a difficulty if you happen to’re engaged on a big Python mission with many programmers at totally different ranges. On this scenario, it’d be good to have a mechanism that ensures strict constants— constants that nobody can change after this system has began.

As a result of Python is a reasonably versatile programming language, you’ll discover a number of methods to attain the objective of creating your fixed unchangeable. In the next few sections, you’ll study a few of these methods. All of them suggest making a customized class and utilizing it as a namespace for constants.

Why do you have to use a category because the namespace on your constants? In Python, any title might be rebound at will. On the module stage, you don’t have the suitable instruments to stop this from occurring. So, it’s essential to use a category as a result of lessons present far more customization instruments than modules.

Within the following sections, you’ll study a number of other ways to make use of a category as your namespace for strict constants.

The .__slots__ Attribute

Python lessons assist you to outline a particular class attribute known as .__slots__. This attribute will maintain a sequence of names that’ll work as occasion attributes.

You received’t be capable of add new occasion attribute to a category with a .__slots__ attribute, as a result of .__slots__ prevents the creation of an occasion .__dict__ attribute. Moreover, not having a .__dict__ attribute implies an optimization by way of reminiscence consumption.

Utilizing .__slots__, you possibly can create a category that works as a namespace for read-only constants:

>>>

>>> class ConstantsNamespace:
...     __slots__ = ()
...     PI = 3.141592653589793
...     EULER_NUMBER = 2.718281828459045
...

>>> constants = ConstantsNamespace()

>>> constants.PI
3.141592653589793
>>> constants.EULER_NUMBER
2.718281828459045

>>> constants.PI = 3.14
Traceback (most up-to-date name final):
    ...
AttributeError: 'ConstantsNamespace' object attribute 'PI' is read-only

On this instance, you outline ConstantsNamespace. The category’s .__slots__ attribute holds an empty tuple, which means that situations of this class can have no attributes. Then you definitely outline your constants as class attributes.

The following step is to instantiate the category to create a variable holding the namespace with all of your constants. Notice that you would be able to shortly entry any fixed in your particular namespace, however you possibly can’t assign it a brand new worth. In the event you attempt to do it, then you definitely get an AttributeError.

With this method, you’re guaranteeing that nobody else in your workforce can change the worth of your constants. You’ve achieved the anticipated conduct of a strict fixed.

The @property Decorator

You may as well benefit from the @property decorator to create a category that works as a namespace on your constants. To do that, you simply have to outline your constants as properties with out offering them with a setter technique:

>>>

>>> class ConstantsNamespace:
...     @property
...     def PI(self):
...         return 3.141592653589793
...     @property
...     def EULER_NUMBER(self):
...         return 2.718281828459045
...

>>> constants = ConstantsNamespace()

>>> constants.PI
3.141592653589793
>>> constants.EULER_NUMBER
2.718281828459045

>>> constants.PI = 3.14
Traceback (most up-to-date name final):
    ...
AttributeError: cannot set attribute 'PI'

Since you don’t present setter strategies for the PI and EULER_NUMBER properties, they’re read-only properties. This implies that you would be able to solely entry their values. It’s not possible to assign a brand new worth to both one. In the event you attempt to do it, then you definitely get an AttributeError.

The namedtuple() Manufacturing facility Operate

Python’s collections module offers a factory function known as namedtuple(). This perform enables you to create tuple subclasses that enable the usage of named fields and the dot notation to entry their gadgets, like in tuple_obj.attribute.

Like common tuples, named tuple situations are immutable, which means that you would be able to’t modify an present named tuple object in place. Being immutable sounds applicable for creating a category that works as a namespace of strict constants.

Right here’s the right way to do it:

>>>

>>> from collections import namedtuple

>>> ConstantsNamespace = namedtuple(
...     "ConstantsNamespace", ["PI", "EULER_NUMBER"]
... )
>>> constants = ConstantsNamespace(3.141592653589793, 2.718281828459045)

>>> constants.PI
3.141592653589793
>>> constants.EULER_NUMBER
2.718281828459045

>>> constants.PI = 3.14
Traceback (most up-to-date name final):
    ...
AttributeError: cannot set attribute

On this instance, your constants play the function of fields within the underlying named tuple, ConstantsNamespace. When you’ve created the named tuples occasion, constants, you possibly can entry your constants through the use of the dot notation, like in constants.PI.

As a result of tuples are immutable, there’s no manner so that you can modify the worth of any subject. So, your constants named tuple object is a full-fledged namespace of strict constants.

The @dataclass Decorator

Data classes are lessons that comprise primarily information, as their title signifies. They will even have strategies, however that’s not their main objective. To create an information class, it’s essential to use the @dataclass decorator from the dataclasses module.

How will you use any such class to create a namespace of strict constants? The @dataclass decorator accepts a frozen argument that permits you to mark your information class as immutable. If it’s immutable, then when you’ve created an occasion of a given information class, you don’t have any technique to modify its occasion attributes.

Right here’s how you should use an information class to create a namespace containing your constants:

>>>

>>> from dataclasses import dataclass

>>> @dataclass(frozen=True)
... class ConstantsNamespace:
...     PI = 3.141592653589793
...     EULER_NUMBER = 2.718281828459045
...

>>> constants = ConstantsNamespace()

>>> constants.PI
3.141592653589793
>>> constants.EULER_NUMBER
2.718281828459045

>>> constants.PI = 3.14
Traceback (most up-to-date name final):
    ...
dataclasses.FrozenInstanceError: can not assign to subject 'PI'

On this instance, you first import the @dataclass decorator. Then you definitely use this decorator to show ConstantsNamespace into an information class. To make the info class immutable, you set the frozen argument to True. Lastly, you outline ConstantsNamespace together with your constants as class attributes.

You possibly can create an occasion of this class and use it as your constants namespace. Once more, you possibly can entry all of the constants, however you possibly can’t modify their values, as a result of the info class is frozen.

The .__setattr__() Particular Methodology

Python lessons allow you to outline a particular technique known as .__setattr__(). This technique permits you to customise the attribute task course of as a result of Python routinely calls the tactic on each attribute task.

In follow, you possibly can override .__setattr__() to stop all attribute reassignments and make your attributes immutable. Right here’s how one can override this technique to create a category that works as a namespace on your constants:

>>>

>>> class ConstantsNamespace:
...     PI = 3.141592653589793
...     EULER_NUMBER = 2.718281828459045
...     def __setattr__(self, title, worth):
...         increase AttributeError(f"cannot reassign fixed 'title'")
...

>>> constants = ConstantsNamespace()

>>> constants.PI
3.141592653589793
>>> constants.EULER_NUMBER
2.718281828459045

>>> constants.PI = 3.14
Traceback (most up-to-date name final):
    ...
AttributeError: cannot reassign fixed 'PI'

Your customized implementation of .__setattr__() doesn’t carry out any task operation on the category’s attributes. It simply raises an AttributeError if you attempt to set any attribute. This implementation makes the attributes immutable. Once more, your ConstantsNamespace behaves as a namespace for constants.

Conclusion

Now you realize what constants are, in addition to why and when to make use of them in your code. You additionally know that Python doesn’t have strict constants. The Python neighborhood makes use of uppercase letters as a naming conference to speak {that a} variable must be used as a relentless. This naming conference helps to stop different builders from altering variables that should be fixed.

Constants are in all places in programming, and Python builders additionally use them. So, studying to outline and use constants in Python is a vital talent so that you can grasp.

On this tutorial, you discovered the right way to:

  • Outline Python constants in your code
  • Determine and perceive some built-in constants
  • Enhance you code’s readability, reusability, and maintainability with constants
  • Use totally different methods to manage and handle constants in a real-world mission
  • Apply varied methods to make your Python constants strictly fixed

With this information about what constants are, why they’re vital, and when to make use of them, you’re prepared to start out bettering your code’s readability, maintainability, and reusability instantly. Go forward and provides it a attempt!





Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Build a Wordle Clone With Python and Rich – Real Python

by learningcode_x1mckf
February 6, 2023
0
Build a Wordle Clone With Python and Rich – Real Python

On this tutorial, you’ll construct your personal Wordle clone for the terminal. Since Josh Wardle launched Wordle in October 2021, thousands and thousands of individuals have performed it....

Read more

Create Interactive Maps & Geospatial Data Visualizations With Python – The Real Python Podcast

by learningcode_x1mckf
February 3, 2023
0
Create Interactive Maps & Geospatial Data Visualizations With Python – The Real Python Podcast

Feb 03, 2023 1h 2m Would you wish to shortly add information to a map with Python? Have you ever needed to create stunning interactive maps and export them...

Read more

Build a JavaScript Front End for a Flask API – Real Python

by learningcode_x1mckf
February 1, 2023
0
Build a JavaScript Front End for a Flask API – Real Python

Most fashionable net functions are powered by a REST API below the hood. That manner, builders can separate JavaScript front-end code from the back-end logic that an online...

Read more

Using the Terminal on Linux – Real Python

by learningcode_x1mckf
January 31, 2023
0
Using the Terminal on Linux – Real Python

The terminal might be intimidating to work with once you’re used to working with graphical consumer interfaces. Nonetheless, it’s an vital device that you have to get used...

Read more

How to Iterate Over Rows in pandas, and Why You Shouldn’t – Real Python

by learningcode_x1mckf
January 30, 2023
0
How to Iterate Over Rows in pandas, and Why You Shouldn’t – Real Python

One of the crucial frequent questions you may need when coming into the world of pandas is easy methods to iterate over rows in a pandas DataFrame. In...

Read more
Next Post
VIDEO INTERVIEW: Azul’s new APAC VP, Dean Vaughan, explains why Azul is the Java solution of choice

VIDEO INTERVIEW: Azul's new APAC VP, Dean Vaughan, explains why Azul is the Java solution of choice

Leave a Reply Cancel reply

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

Related News

What Is Bun.js and Why Is the JavaScript Community Excited About It?

What Is Bun.js and Why Is the JavaScript Community Excited About It?

September 21, 2022
Java Developer at RMB – IT-Online

Java Developer at RMB – IT-Online

November 15, 2022
Solutions Architect Java JavaScript Cloud – Semi Remote – R850 per hour at e-Merge IT Recruitment

NEW WORK: Senior C# JavaScript Developer @ Remote dev shop – R850k at e-Merge IT Recruitment – Gauteng Johannesburg

January 28, 2023

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • JobRunr, the Java Scheduler Library, Released Version 6.0 – InfoQ.com
  • An Introduction to Lodash and Its Benefits for JavaScript Developers – MUO – MakeUseOf
  • "Used properly, Python is not slower than C++" – eFinancialCareers (US)

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?