Modules / Módulos - Coding Basics #16

from newpost import modules


PythonModules.webp

Shoutout to Real Python

HiveDivider.png

In this article you'll find:

  • Introduction
  • What is a module?
  • What does a module look like in code?
  • Importing elements from modules
  • Creating our own modules

HiveDivider.png

In all the posts we have seen so far, we went over the most important elements of object-oriented programming and programming. However, all of this was done in a single file.

Now, it is time to start working with external elements to our IDE. That's why, we will make an introduction to modules.

You see, whether you want to import a library that is not present by default in your programming language or you want to create a function in a file to be used in another file, modules will always be a must-do.

So, if you want to become a master of modules and take your programming skills to the next level, read on.

Let's get started!

HiveDivider.png

What is a module?


TechVidVan.webp

Shoutout to TechVidVan

A module is a file that contains the code required to perform a specific action. This means that it can have functions, variables, classes, etc...

So, if you have the code to perform an action, why not write it inside the same file?

This is because as our program grows, so do the lines of code. If a program happens to have too many lines of code, it will become much more difficult to organize and maintain, where a simple syntax error can give us a headache for hours.

This is why we prefer to create functions in different files (which we call modules), which we simply call from our main file.

An example of this can be seen in a program with information about hotels. In this we will have different options, where we can consult the location, the available rooms and the facilities provided by the facilities.


image.png

Lots of functions and variables inside a single file

In the first example, we will see a program with a high degree of complexity, where we will have a large number of variables and functions that we will have to invoke when we need to verify information. This can lead to great confusion.


image.png

Functions and Variables in different files to the main one

However, looking at the second example, we can see that we separate Room, Facilities and Location into distinct files, which makes looking up this information as easy as importing them.

Python comes with a large number of modules, allowing us to import some that allow us to control the operating system, and the destination of our files (These are named built-in modules). However, the most common way in which modules are used is to import libraries that we download and plan to add to our program (e.g. Flask, which will help us to create the backend of web applications).

Now that we know how the modules look like in principle, how is their syntax?

HiveDivider.png

What does a module look like in code?


w3resource.png
Shoutout to w3resource

When we want to import a particular module everything will depend on the particular instruction for each programming language. In the case of Python, we use the import statement. Seeing this, we can use a commonly used library such as math, which allows us to access mathematical functions based on the c language.

import math

With this, we will gain access to all functions, classes and variables present in os. Now, if we want to use one of the functions or variables in the module, we will have to precede the name of these with the module. For example, to see the value of pi:

import math

print(math.pi)

>>>
3.141592653589793

Now, we don't necessarily have to place math. We can also alias our method with the word "as". So, if we want to call math as m, what we should do is to write:

import math as m

Thus, when calling it we only have to write:

print(m.pi)

>>>
3.141592653589793

HiveDivider.png

Importing elements from modules


Medium.png

Shoutout to Felipe F Garcia from Medium

We may not always want to import the whole module, sometimes we only want to use a specific function. This allows us to:

  • Save space
  • Avoid having to use the module name as a prefix when calling the function.

For example, if we want to call the pi constant in the previous example without having to use math.pi, we only have to define:

from math import pi

We see that we use from, to identify the library where is the function, variable or class that we want to call and finally, we place import followed by the current name of the constant.

Thus, when printing the value of pi:

print(pi)

>>> 3.141592653589793

Another way to avoid having to use the module name at the beginning is to import all the names into the library. This, using:

from math import *

This way, when we have to use elements inside this module, it will not be necessary to write math.(Name of the element).

HiveDivider.png

Creating our own modules


Educative.io.png

Shoutout to Educative.io

In Python, creating a module is as simple as creating two files inside a folder. One will correspond to the main file, where we will call the other file or "module", and the other to the module itself in what is known as a user-defined module.

So, we have two files, one called main.py (Main program) and sumfunction, which will be our module.

image.png

Inside sumfunction, we have the following code:

def sum_function(a,b):
    result = a + b
    return result

Now, we want to use this function without having to rewrite it in main.py. To do this, we go to main and inside it we write:

from sumfunction import sum_function

And then, to use the function, we do the same as if it were written in the file.

print(sum_function(2,4))

>>> 6

Note: If we want to import the modules from a folder that is in the same directory as the file from which it is called, we only have to place

from foldername.filename import (Name of the element) 

image.png

HiveDivider.png

Once we get past the basics, the use of modules becomes essential, allowing us to add new functionality to Python to carry out endless projects.

After reading this article you will have mastered modules, allowing you to add new possibilities to your programming language journey.

HiveDivider.png

Thanks for your support and good luck!

HiveDivider.png

@jesalmofficial.png

HiveDivider.png

from newpost import modules


PythonModules.webp

Shoutout to Real Python

HiveDivider.png

En este artículo encontrarás:

  • Introducción
  • ¿Qué son los módulos?
  • ¿Cómo se ve un módulo en código?
  • Importando elementos desde módulos
  • Creando nuestros propios módulos

HiveDivider.png

En todos los posts que hemos visto hasta ahora, fuimos sobre los elementos más importantes de la programación y programación orientada a objetos. Sin embargo, todo esto se realizaba en un solo archivo.

Ahora, es tiempo de empezar a trabajar con elementos externos a nuestro IDE. Es por eso, que haremos una introducción a los módulos.

Verás, ya sea que quieres importar una librería que no está presente por defecto en tu lenguaje de programación o que quieras crear una función en un archivo para que sea usada en otro archivo, los módulos siempre serán un must-do.

De esta forma, si quieres convertirte en un maestro de los módulos y llevar tus habilidades de programación al siguiente nivel, sigue leyendo.

¡Comencemos!

HiveDivider.png

¿Qué es un módulo?


TechVidVan.webp

Shoutout to TechVidVan

Un módulo es un archivo que contiene el código requerido para realizar una acción específica. Esto significa que puede tener funciones, variables, clases, etc...

Entonces, si tiene el código para realizar una acción ¿Por qué no escribirlo dentro del mismo archivo?

Esto se debe a que a medida que nuestro programa crece, las líneas de código también lo hacen. Si un programa pasa a tener demasiadas líneas de código, se hará mucho más difícil de organizar y mantener, donde un simple error de syntax nos puede dar un dolor de cabeza por horas.

Es por esto que preferimos crear funciones en distintos archivos (A los cuales llamamos módulos), los cuales simplemente llamamos desde nuestro archivo principal.

Un ejemplo de esto se puede ver en un programa con información sobre hoteles. En este tendremos distintas opciones, donde se puede consultar tanto la ubicación, las habitaciones disponibles y las facilidades que otorgan las instalaciones.


image.png

Montones de funciones y variables dentro de un solo archivo.

En el primer ejemplo, veremos un programa con un grado de complejidad alto, donde tendremos gran cantidad de variables y funciones que tendremos que invocar cuando requiramos verificar información. Esto nos puede llevar a grandes confusiones.


image.png

Funciones y variables en distintos archivos al principal

Sin embargo, viendo el segundo ejemplo, podemos ver que separamos a Room, Facilities y Location en archivos distintos, lo que hace que buscar esta información sea tan fácil como importarlas.

Python trae una gran cantidad de módulos, permitiéndonos importar algunos que nos permiten controlar el sistema operativo, y el destino de nuestros archivos (Estos son conocidos como módulos built-in). Sin embargo, la forma más común en que suelen usarse los módulos es para importar librerías que descargamos y pensamos añadir a nuestro programa (Ej: Flask, que nos servirá para crear el backend de aplicaciones web).

Ahora que sabemos como se ven los módulos en principio, ¿Cómo es su sintaxis?

HiveDivider.png

¿Cómo se ve un módulo en código?


w3resource.png
Shoutout to w3resource

Cuando queremos importar un módulo en particular todo dependerá de la instrucción particular para cada lenguaje de programación. En el caso de Python, usamos la instrucción import. Viendo esto, podemos usar una librería usada comúnmente como lo es math, que nos permite acceder a funciones matemáticas basadas en el lenguaje c

import math

Con esto, ganaremos acceso a todas las funciones, clases y variables presentes en os. Ahora, si queremos usar una de las funciones o variables en el módulo, tendremos que preceder el nombre de estas con el módulo. Por ejemplo, para ver el valor de pi:

import math

print(math.pi)

>>>
3.141592653589793

Ahora bien, no necesariamente tenemos que colocar math. También podemos colocarle un alias a nuestro método con la palabras "as". Así, si queremos llamar a math como m, lo que debemos hacer es escribir:

import math as m

Así, al llamarla solo tenemos que escribir:

print(m.pi)

>>>
3.141592653589793

HiveDivider.png

Importando elementos desde módulos


Medium.png

Shoutout to Felipe F Garcia from Medium

No siempre querremos importar todo el módulo, a veces, solo queremos usar una función específica. Esto nos permite:

  • Ahorrar espacio
  • Evitar tener que usar el nombre del módulo como prefijo cuando llamemos la función.

Por ejemplo, si queremos llamar a la constante pi del ejemplo anterior sin tener que usar math.pi, solo tenemos que definir:

from math import pi

Vemos que usamos from, para identificar la librería donde está la función, variable o clase que queremos llamar y finalmente, colocamos import seguido por el nombre actual de la constante.

Así, a la hora de imprimir el valor de pi:

print(pi)

>>> 3.141592653589793

Otra forma de evitar tener que usar el nombre del módulo al principio es importando todos los nombres dentro de la librería. Esto, usando:

from math import *

Así, cuando tengamos que usar elementos dentro de este módulo, no hará falta escribir math.(Name of the element).

HiveDivider.png

Creando nuestros propios módulos


Educative.io.png

Shoutout to Educative.io

En python, crear un módulo es tan sencillo como crear dos archivos dentro de una carpeta. Uno corresponderá al archivo principal, donde llamaremos al otro archivo o "módulo", y el otro al módulo en si (En lo que se conoce como un módulo definido por el usuario).

Así, tenemos dos archivos, uno llamado main.py (Programa principal) y sumfunction, que será nuestro módulo.

image.png

Dentro de sumfunction, tenemos el siguiente código:

def sum_function(a,b):
    result = a + b
    return result

Ahora, queremos usar esta función sin tener que reescribirla en main.py. Para hacer esto, nos dirigimos a main y dentro de este escribimos:

from sumfunction import sum_function

Y luego, para usar la función, realizamos lo mismo que si estuviera escrita en el archivo.

print(sum_function(2,4))

>>> 6

Nota: Si queremos importar los módulos desde una carpeta que se encuentra en el mismo directorio que el archivo desde donde se llama, solo tenemos que colocar

from foldername.filename import (Name of the element) 

image.png

HiveDivider.png

Una vez que pasamos los básicos, el uso de módulos se hace esencial, permitiéndonos agregar nuevas funcionalidades a Python para llevar a cabo un sin fin de proyectos.

Tras leer este artículo habrás dominado los módulos, permitiéndote agregar nuevas posibilidades a tu viaje de los lenguajes de programación.

HiveDivider.png

¡Muchas gracias por tu apoyo y buena suerte!

HiveDivider.png

@jesalmofficial.png



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000