How to run a module in Python?

Asked

Viewed 1,008 times

1

have a question. A few days ago I am creating an application with GUI interface to show movie schedules. It was built in modules, for example, a module takes care of the images, searches the web and download. Another module takes care of other information such as looking for synopsis, film budgets, actors. Another, takes care of picking up schedules and information from the cinema and another from the GUI.

My question is, how to connect these modules? Because not everything in the module is within function. The imaging module lowers the film covers by means of a is out of a function.

How do I get my main module to run all the module code? I have to turn everything into a function?

This project is being done only to help me learn. Thanks in advance :)

  • The @nbro answer is appropriate to your question. On the other hand, there is a comment to be made. Many consider it a bad practice to put executable instructions in their modules (or on __init__.py of your Packages). The argument is that it is an unexpected behavior. When you import a module you normally expect it to just define some objects (constants, classes, functions, etc.) If your modules have too much code like this, one day it may be difficult to understand some bug or move things from one module to another. At least I’ve experienced this kind of problem a few times.

1 answer

1

When you matter a module, if you have code at module level (like your for loop), this will run at that very moment. So if you want at the time of import any code runs immediately, you can make that code global (like your for loop), or you can encapsulate it in a function, and call it directly from your module or module where it is set.

For example, suppose I have the following module A:

# módulo A

# código global
for i in range(10):
    print(i)

# função qualquer
def some_function():
    print("some function")

That you want to import in the following module B:

# módulo B

import A  # importando módulo A

A.some_function()

The exact moment you care A, the for loop will be executed immediately because this is not encapsulated in a function. Note well that the code of the function some_function is executed because I’m calling her.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.