Is the import valid if the __name__ == '__main__' section?

Is it possible to place a statement import

at the top of a section if __name__ == '__main__'

rather than at the top of a script if the module is only used when the script is directly executed?

Example:

def open_as_clean_list(filename):
    list = []
    with open(filename) as f:
        for line in f:
            li = line.rstrip()
            if not li.startswith("#") and li:
               list.append(li)
        return list

if __name__ == '__main__':
    import random

    first = open_as_clean_list("first.txt")
    second = open_as_clean_list("second.txt")
    print(random.choice(first) + ' ' + random.choice(second))

      

As you can see, this random

is only required if the code is run directly. Is it best to import anyway, or only import when directly executed? Does it matter what the module actually is?

+3


source to share





All Articles