Python Forum
Importing a function from another file runs the old lines also
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Importing a function from another file runs the old lines also
#1
I'm trying to import a function, an "def" function, to a new file, but when i do, the old line ABOVE are also read. Why!?
Reply
#2
When asking questions about your code it is a good idea to post the code.

When you import a file the first time it is evaluated to get all the variables, functions and classes. If you have code you don't want evaluated you need to hide it inside a function or behind a conditional. The code below has a print statement that prints when the code is evaluated. This will occur if the file is executed or the first time the file is imported. Additional prints are hidden inside functions or behind a condition that is only True if this file is being executed.
"""Interesting function"""
def my_func(arg):
    print("this code is protected until my_func is called")
    return arg + arg**2 + arg**3

print("this code is not protected")

if __name__ == '__main__':
    """This code is only executed when running this file from the command line"""
    print("call my_func")
    my_func(1)
When I run this file from the command line I see this:
Output:
this code is not protected call my_func this code is protected until my_func is called
When I import this this module I see this:
Output:
this code is not protected
Notice the code protected by the conditional is not executed.
Reply
#3
This file is called "Testfile0

print("lowest number//")
print(min(4, 40404))
print(sqrt(25))

def calcus():
    print("Why are the files above read?")
]

This is another file
from Testfile0 import calcus


calcus()
Yoriz write Jul-06-2021, 06:12 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#4
Your Testfile0 should be written like this:
import math

"""expose these functions"""
def calcus():  # <- Want to see this function
    pass

if __name__ == '__main__':
    print("lowest number//")   # Only execute if run as "python Testfile0.py"
    print(min(4, 40404))
    print(math.sqrt(25))
Reply
#5
#Testfile0

import math

print("lowest number//")
print(min(4, 40404))
print(sqrt(25))

"""expose these functions"""


def calcus():  # <- Want to see this function
    print("This is what i want only")
    pass

if __name__ == '__main__':
    print("lowest number//")  # Only execute if run as "python Testfile0.py"
    print(min(4, 40404))
    print(math.sqrt(25))
#Calculator
from Testfile0 import   calcus
calcus()
Reply
#6
You're not listening.
When you import a function from a file, it starts reading at the beginning of the file and will execute the code. def protects code from being run (only runs when the function is called). Anything that is not in a function definition will be executed. And, actually that includes that last block of code but since the if condition is not met those lines are skipped.

So, on import, your first 3 print lines will execute. The function will be defined. The if statement tested and fails so the last 3 prints do not occur.
Reply
#7
Look at comments to see what Python does when importing this file the first time.
import math    # Imports math.  evaluates math if this is the first import
 
print("lowest number//")  # evaluates print command which prints to stdout
print(min(4, 40404))  # evaluates min command which returns 4.  evaluates print command which prints to stdout
print(math.sqrt(25))  # evaluates sqrt command which returns 5.  evaluates print command which prints to stdout
 
"""expose these functions"""
 
 
def calcus():  # <- # Evaluates function declaration.  Adds function named "calculus" with no arguments to module namespace
    pass
 
if __name__ == '__main__':  # Evaluates if __name__ == '__main__'.  Is not True, so skip following INDENTED lines
    print("lowest number//")
    print(min(4, 40404))
    print(math.sqrt(25))
If you don't want those print statements to print anything, don't put them where they will be evaluated!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to do 100 runs simulation based on the current codes? dududada 6 973 Sep-03-2023, 01:43 PM
Last Post: deanhystad
  New2Python: Help with Importing/Mapping Image Src to Image Code in File CluelessITguy 0 721 Nov-17-2022, 04:46 PM
Last Post: CluelessITguy
  Another program runs bho68 7 1,179 Nov-08-2022, 08:16 PM
Last Post: bho68
  Delete multiple lines from txt file Lky 6 2,284 Jul-10-2022, 12:09 PM
Last Post: jefsummers
  Problem with importing Python file in Visual Studio Code DXav 7 5,071 Jun-15-2022, 12:54 PM
Last Post: snippsat
  importing functions from a separate python file in a separate directory Scordomaniac 3 1,365 May-17-2022, 07:49 AM
Last Post: Pedroski55
  failing to print not matched lines from second file tester_V 14 6,073 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  Extracting Specific Lines from text file based on content. jokerfmj 8 2,953 Mar-28-2022, 03:38 PM
Last Post: snippsat
  [Solved] Trying to read specific lines from a file Laplace12 7 3,527 Jun-21-2021, 11:15 AM
Last Post: Laplace12
  all i want to do is count the lines in each file Skaperen 13 4,817 May-23-2021, 11:24 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020