'How to properly use import in Python

In a python file I have 2 classes Node and LinkedList and after that some operations using those classes like below

node1 = Node("a")
node2 = Node("b")
node3 = Node("c")

linkedList = LinkedList()
linkedList.insert(node1)
linkedList.insert(node2)
linkedList.insert(node3)

linkedList.print()

In another python file I have imported Node and LinkedList classes

from create_singly_ll import Node, LinkedList

When I run this second file, I am getting output of the print linked list. I don't want that when I run 2nd file the operations outside the imported class run.



Solution 1:[1]

You should put the code you don't want to run in a if __name__ == '__main__' block :


<Your classes definition here>

if __name__ == '__main__'
    node1 = Node("a")
    node2 = Node("b")
    node3 = Node("c")

    linkedList = LinkedList()
    linkedList.insert(node1)
    linkedList.insert(node2)
    linkedList.insert(node3)

    linkedList.print()

The code in such a if block will only run if you run the file directly, but not if you import it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 qcoumes