Dev Env
Dev Env

Reputation: 5

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.

Upvotes: 0

Views: 33

Answers (1)

qcoumes
qcoumes

Reputation: 517

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.

Upvotes: 1

Related Questions