testing code

Sharan Basappa sharan.basappa at gmail.com
Sun Jul 8 00:21:57 EDT 2018


On Saturday, 7 July 2018 18:22:23 UTC+5:30, Chris Angelico  wrote:
> On Sat, Jul 7, 2018 at 10:02 PM, Sharan Basappa
> <sharan.basappa at gmail.com> wrote:
> > On Friday, 6 July 2018 09:22:31 UTC+5:30, Chris Angelico  wrote:
> >> On Fri, Jul 6, 2018 at 12:56 PM, Sharan Basappa
> >> <sharan.basappa at gmail.com> wrote:
> >> > Please let me know if the following understanding of mine is correct.
> >> > I need to put the program code in a separate file and organize every executable code in some form of function. If any code exists outside of function then it is not executable by importing.
> >> >
> >>
> >> Kinda. It's actually the other way around: if any code exists outside
> >> of functions, it will be executed immediately when you import. So
> >> you're correct in that it would be hard (maybe impossible) to
> >> unit-test that; and yes, the normal way to do it is to put all your
> >> important code into functions.
> >>
> >> ChrisA
> >
> > Chris,
> >
> > Things do work as per expected with one exception.
> > You mentioned that as soon as a file is imported, it executes immediately.
> >
> > Please see the example below:
> >
> > file: test_2.py
> >
> > x = 10
> > y = 20
> >
> > c = x-y
> >
> > print c
> >
> > def func1():
> >     return x+y
> >
> > test_2_test.py
> >
> > x = 10
> > y = 20
> >
> > c = x-y
> >
> > print c
> >
> > def func1():
> >     return x+y
> >
> > this is the output:
> > %run "D:/Projects/Initiatives/machine learning/programs/test_2_test.py"
> > 30
> >
> > As you can see, print c in test_2 file was not executed upon import as there is no corresponding output
> 
> I don't think you import your other module anywhere.
> 
> ChrisA

sorry. there was a copy paste error when i posted. I pasted test_2.py for both the files:

here are the files again. The issue remains.

test_2.py:
x = 10
y = 20

c = x-y

print c

def func1():
    return x+y 

test_2_test.py:
import test_2

x = test_2.func1()
print x

output:
%run "D:/Projects/Initiatives/machine learning/programs/test_2_test.py"
30


More information about the Python-list mailing list