Importing Modules: 4 types of imports

A Module(or package as they are referred as in other languages) is a collection of code accessible using an import statement. Simply put, a module is a file containing Python code. It may have variables, functions, classes, print statements etc. Modules allow you to logically organize your code, putting related stuff in a single module. This makes the code easier to comprehend and easier to work with. You can import a module in 4 different ways:

import some_module

import some_module as alias

from some_module import *

from some_module import some_func

Expand the following code snippet for more details.

############################## 1. import some_module ##########################
# Say, you have come up with an elementary yet handy function that tells whether the number supplied to it is odd or even. It should look something like this:
def oddOrEven(number):
if number % 2 == 0:
print(number,"is even.")
else:
print(number, "is odd.")
# Now, you wish to use the above function in some other program without having to type it again. So you decide to put it inside a .py file, say myModule.py. Place it anywhere on your computer. In the same folder, create another file, say, main.py, and open it with IDLE.
import myModule
myModule.oddOrEven(31)
myModule.oddOrEven(18)
### OUTPUT ###
31 is odd.
18 is even.
# This is the basic import statement in action i.e. import some_module. The basic import statement is executed in two steps:
# -> find the said module, load the code in it
# -> define a name or names in the local namespace for the scope where the “import” statement occurs.
# The 'local namespace' contains all the identifiers of the program. So the import statement brings the identifiers of the module in the namespace of the program in which the import statement is written.
# In order to import multiple modules in a single statement:
>>> import module1, module2, module3
# The above will execute the aforementioned dual steps for each module separately, just as if they were written in different import statements one after the other.
############################## 2. import some_module as alias ##############################
# Python allows us to refer to the imported module by giving it a convenient name. The name thus given is known as the alias of the module in the current program.
import myModule as specialFunctions
specialFunctions.oddOrEven(31)
specialFunctions.oddOrEven(18)
### OUTPUT ###
31 is odd.
18 is even.
############################## 3. from some_module import * ##############################
# This type of import statement is used when we do not want to qualify the imported functions i.e. if we are trying to call oddOrEven() imported from module myModule, we will call it by oddOrEven(num) and not by myModule.oddOrEven(num).
from myModule import *
oddOrEven(31)
oddOrEven(18)
### OUTPUT ###
31 is odd.
18 is even.
############################## 4. from some_module import some_func ##############################
# To import a specific function from a module, from some_module import * is used. This variant is handy when only few selected portions of code are to be imported from a large module.
from myModule import oddOrEven
oddOrEven(31)
oddOrEven(18)
### OUTPUT ###
31 is odd.
18 is even.

Terminating your program

In order to exit from a Python script/Interactive Interpreter Session/Command Prompt Session, any of the following functions can be used: exit(), quit(), sys.exit(). While calling these functions, you can provide an exit_code as the first argument. These exit codes can be used in bash scripting, where the special variable $? returns the last exit status.

Asserting values using assert keyword

It's hard to argue with the fact that all practical programs have bugs. It is better to find them beforehand and strangle them before they bother the testing team. A developer tries to minimises the occurrence of these defects, by writing self-checks to ensure that things are going as he plans. The assert statement helps to achieve this purpose. The assert statement takes an expression and if it is true, it continues the program flow. Else, it raises an AssertionError. Let's take a look at an example.

Assertions serve as safety nets, providing a way to check that the state of the program is as per the expectations of the developer. The developer might have some assumptions as he is writing the code, which can be made explicitly obvious with assert statements. This is in conformance with the Zen of Python, which states that "Explicit is better than implicit."

The assert statement takes an optional second option, which can be used to give an elaborate explanation of the failure detected. This can also include cleanup code.

Number System Interconversion: int(), bin(), oct() & hex()

To convert these strings back into decimal system, use the builtin int() function with appropriate base value.

>>> int('0b100', 2)
4
>>> int('0x4', 16)
4
>>> int('0o4', 8)
4

You can use the combination of these methods to convert one non-decimal system to another. For example, converting a binary value to its hexadecimal equivalent:

>>> hex( int('0b100', 2) )
'0x4'

Serialization in Python: pickle, shelve & json modules

The process of converting native language objects into a sequence of bytes or objects of an interchange format, which are either stored in a file or stored in a string, for the purpose of loading the data in a different session, or for transmitting the data over the network, is known as Serialization. Saving the state of a game when you exit it, and loading it when you launch the game next time, is one such example where serialization is implemented. We’ll discuss 3 modern-day Python modules which implement serialization: pickle, shelve and json.

Expand the following code snippet to view basic examples of serialization using these 3 modules. For further details, have a look at this post.

Changing Data Types: Type Casting

Python identifiers do not carry any information about their type while declaration. As soon as a value is assigned to an identifier, Python determines the data type of the identifier, and gives it its own set of associated functions depending on the data type. There are instances when you need to explicitly convert one data type into another. For this purpose, Python provides numerous builtin functions. For example, in order to convert a string identifier into an integer, we can use the int() function.

Similarly, Python provides these functions: str(), float(), complex(), bool(), chr(), bin(), oct() & hex(). You can use the builtin help function to know how to use these.

Creating isolated Python environments using virtualenv

Creating isolated Python environments is a great industrial practice to keep two or more applications separate from each other. These applications have different dependencies, e.g. one may use 1 version of an imported library and the other may use another version of it. To keep both these applications stable and unmangled from each other, it's best to create two different Python environments to avoid the hassle of why-is-this-application-running-and-why-is-this-not.

The Cheese Shop provides a library called virtualenv which helps the developers to create separate Python environments. Using this library, you can create a standalone Python environment for a project with a simple command. This standalone copy of Python has pip with it, which you can use to install libraries you need only for this project. These libraries will not be installed in the global copy of Python you have on your system. In order to recreate the same environment on another system, virtualenv enables us to create a text-file of all the installed libraries which you can provide to the new environment during its creation, and it will install them one-by-one on its own. Furthermore, virtualenv also allows you to choose which version of Python you want to work with by specifying it during environment creation command.

For details on how to do all this, check this post out on Creating isolated Python environments using virtualenv.

Using Lambda Expressions (Anonymous functions)

Lambda expressions(a.k.a. lambda forms) in Python are used to create anonymous functions. In a nutshell, these functions do not have the def keyword, instead have a lambda keyword, take any number of arguments and return a single value in the form of an expression.

Lambda expressions may not necessarily enhance readability, but they help in making the code compact, as they replace elementary functions which return a single expression.

In actuality, lambda is the basic form of a function definition. Any function, in principle, is a lambda assigned to a variable. The expression "lambda arguments: expression" yields a function object. The unnamed object behaves like a function object defined with

def (arguments):
return expression

Keep in mind that:

Lambda expressions cannot contain statements.

Lambda expressions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Lambda expression are extremely useful in GUI Programming. They serve as callback functions.

In a broad sense, anything you can do with a lambdas, you can achieve the same with named functions, or lists. However, it’s up to you to choose whether to use lambdas or not. You could decide based on the readability of your code.

l = lambda x: x + 2 is the same as def l(x): return x + 2

Using semi-colon (;) to delimit statements in a suite

Python uses new-lines as statement delimiters. This is in contrast to many contemporary languages which use semi-colons to delimit statements. However, Python also allows to use semi-colons. A clause in Python, consists of a header and a suite. For example, the def clause, used for defining functions, will have 'def functionName():' as header while the statements constituting the functionBody will serve as the associated suite. You can put semi-colon delimited statements in suites to put multiple statements on the same line.

The reason why this is allowed is a design decision on the part of Python developers. While this is not a necessary feature of Python, it is certainly nice to have.

Logging using logging module

The standard library logging helps you to log events of different severities to a file or the standard output in interpreter. This is particularly helpful in large applications where you would like to record events as they occur for future reference. Expand the following snippet for an example of logging. To know more about the logging module, I suggest you view this article.