Mauro Matsudo
Mauro Matsudo

Reputation: 25

How to declare the return of a function as the default parameter to another function without calling the first function?

It seems a litle confuse, but my task is the following:

I have a personalyzed python module named functions, where I declare many tasks that are often used in my project. One of these functions is read_servers_list(), this gets a list of servers that an action will be done in. Another function is called automation(command, servers, mixed = False, logs = False, csv = False) which is responsible for a repetitive task in the servers list defined by the user. Most times, the servers in automation() are get by the read_servers_list () functions, so i set it as the default value automation(servers -read_servers_list ()). But I got a problem, when I import the function module into another module (import functions), the read_servers_list() is executed twice, once during the import action and another when I use the functions.automation().

Could someone help me, I wish to import the functions and execute the read_servers_list() only when it is called.

Upvotes: 0

Views: 41

Answers (2)

Rineesh Konaparthi
Rineesh Konaparthi

Reputation: 104

I simulated your scenario below:

  1. My functions.py:
def read_servers_list():
    return ["server1", "server2", "server3"]


if __name__ == "__main__":
    print(read_servers_list())
  1. My main_code.py
import functions

print(functions.read_servers_list())

When I use if __name__ == "__main__", the code block below it will be executed only when the called function is itself. This will avoid calling the main part of your import functions.

Upvotes: 0

Carcigenicate
Carcigenicate

Reputation: 45771

Just have the default as None, then check for that in the function:

def automation(command, servers=None, mixed=False, logs=False, csv=False):
    if servers is None:
        servers = read_servers_list()
    . . .

The default arguments get evaluated regardless of whether or not they're used. If you want to delay them being called until they're actually needed, run them in the function instead.

Upvotes: 2

Related Questions