Python Programming Language

This post explains some aspects specific to Python programming language.

If you want to read a more general introduction to Python and not only the programming language itself (including how to learn Python or getting support on Python), please read this post.

Python Modules

What are Python modules?

Python modules allow to add to your computer libraries, functionalities and tools already done, tested and provided by others. This enables reusability of code, and avoid having to develop your own tools and functionalities when someone else (or yourself previously) have already developed them and made them available.

You can find more information about Python modules on this post.

Which uses have Python modules?

There are Python modules for several uses, as for example:

  • Data visualization
  • Game development
  • Graphical User Interface (GUI)
  • Machine learning
  • Web development

You can find many examples of popular Python modules grouped by category on this post.

Documenting Python Code

Python document strings or docstrings is the standard way of document source code within itself. You can find some examples of how to use it on this external link.

The way it works is defined in document PEP 257 “Docstring conventions”. You can read it on this external link.

reStructuredText, abbreviated reST, is a tool included in library Doctools. You can read more about it on this external link.

Sphinx seems to be another convention to document source code.

Understanding Decorators

A decorator is a function that takes the output of another function and transform it to a new one; maybe, it is a “cleaner” output and this is why it is called decorator.

To understand how to use decorators in Python, you can have a look at this external link.

An example of use of decorator in Python standard library is pytest.fixture, that allows to pass preset test data as parameters to test functions.

Programming Solutions to common Problems in Python

This sections contains solutions to some common doubts or problems that appear when using Python.

Copy a list

Use a code like this:

list = ['apple', 'pear']

list_copy = list[:]

list_copy will be a perfect copy of list. If you change list_copy, list will be unaltered.

Check whether a keyword exists in a dictionary

To check if a keyword exists in a dictionary, use the expression “in” like this:

keyWord in list

Example:

dict = {'name'='John', 'surname'='Smith'}

keyWord = 'name'

if(keyWord in list):
  print(f"The keyword {keyWord} exist!")
  print(f"The value for that keyword is {dict[keyWord]}
else:
  print(f"The keyword {keyWord} doesn't exist")

If you try to access a keyword that doesn’t exist within a dictionary, you will get an execution error, so it is better to do this check.

Check that all Values within a List exist in a Set

You can use the function all() the check that all values within a list exist in a set:

my_list = [1, 2, 3]
my_set = {1, 2, 3, 4, 5}

all_in_set = all(value in my_set for value in my_list)

if all_in_set:
    print("All values in list are in set")
else:
    print("Not all values in list are in set")

It is using the generation expression inside the all() function:

  • value in my_set: This is the condition that checks whether each value in my_list is in my_set. It returns True if the value is in the set, and False otherwise.
  • for value in my_list: This is the loop that iterates over each value in my_list. For each value, the value in my_set condition is evaluated.

The all() functions checks that all values within the list generated by the generation expression are true.

Using a Variable in an imported file

You can pass a variable included data when calling an imported function from a file.

Using Colours in command-line Interfaces

You can use colours in a command-line interfaces using the module Colorama.

This is an example on how to use Colorama:

import colorama

# Initialize colorama
colorama.init()

# Print red text
print(colorama.Fore.RED + "Hello, world!" + colorama.Style.RESET_ALL)

Passing Optional Arguments to a Function

You can pass optional arguments through positional arguments, arbitrary arguments or arbitrary keyword arguments.

For positional arguments, you can pass an optional argument to a function by assigning a void value in the function definition.

def get_full_name(first_name, last_name=''):
    if(last_name):
        full_name = first_name + ' ' + last_name
    else 
        full_name = first_name
    return full_name

ut_fullname = get_full_name('utnapishtim')
ab_fullname = get_full_name('abraham','lincoln')

For arbitrary keywords, you pass an argument starting with one asterisk (*) that is usually called args (from arguments):

def get_full_name(first_name, *args):
    full_name = first_name
    for arg in args:
        full_name += ' ' + arg
    return full_name

get_full_name('wolfgang','amadeus','mozart')

For arbitrary keyword arguments, you pass an argument starting two asterisk (**) that is usually called kwargs (from keywords arguments)

def get_full_name(first_name, **kwargs):
    full_name = first_name
    if 'middle_name' in kwargs:
        full_name += ' ' + kwargs['middle_name']
    if 'last_name' in kwargs:
        full_name += ' ' + kwargs['last_name']

get_full_name('wolfgang',middle_name='amadeus',last_name='mozart')

Calling a Method dynamically

Python allows to call a method dynamically, meaning that you can decide the name of the method you want to call on running time.

This is useful, for example, if you need to run an specific function within a set of functions depending on a result that cannot be expected in advanced.

class_instance = ClassExample()
return_value = getattr(class_instance, "method_name")()

Getting a Variable dynamically

Python allows to call a variable dynamically, meaning that you can decide the name of the variable you want to use on running time.

This is useful, for example, if you need to get a variable or another depending on a result that cannot be expected in advanced.

If the variable is global:

globals()["variable_name"]

If the variable is dynamic:

locals()["variable_name"]

Getting a Function dynamically

Python allows to call a function dynamically, meaning that you can decide the function of the variable you want to use on running time.

This is useful, for example, if you need to call a function or another depending on a result that cannot be expected in advanced.

If the function is local

def my_function(x, y):
    return x + y

# Call the function with parameters by name using globals()
function_name = "my_function"
function = globals()[function_name]
result = function(3, 4)
print(result)  # Output: 7

Note that this approach assumes that the function is defined at the global scope of your Python program. If the function is defined within a module or a class, you will need to use the importlib module to dynamically import the module or the class, and then use the getattr() function to get the function by name.

Leave a Reply

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