[Tutor] just a quick logic check if someone has two seconds

Alan Gauld alan.gauld at yahoo.co.uk
Thu Aug 1 20:27:40 EDT 2019


On 01/08/2019 23:10, nathan tech wrote:

> 
> import speedtest

This is not a standard library module so I have no idea
what it does so obviously there could be magic afoot of
which I am unaware. But assuming it behaves like most
Python code...

> def do-test():
>   test=speedtest.Speedtest()
>   test.download()
>   test.upload()
>   return [test.download_speed, test.upload_speed]

test is garbage collected sat this point since it
goes out of scope and the returned values are passed
to the caller. Note that the returned values are not
part of the test object. The test attributes refer to
those values but it is the values themselves that
are returned.

> Now. If I was to put this into a GUI application, I was thinking of 
> having it something like this:

The fact it is a GUI is completely irrelevant.
There is nothing special about how a GUI calls a function.

> user clicks button,
> button calls function which:
> 
> 1. Shows the screen which updates with test status.
> 2, does: results=do_test()
> 3. Updates the screen with the contents of results.

The fact that the GUI calls this function is irrelevant.
A function gets called and performs some actions.
One of which is to call do_test(). It would be exactly the same if you
did this:

for n in range(3):
   result = do_test()
   print(result)

You still call the function repeatedly.

> If the user clicks the button, say, 3 times, will I have three separate 
> speedtest objects?

You will have created 3 separate speedtest instances and each
will have been garbage collected when do_test() terminated.
So you will have no speedtest instances left hanging around.

> or will the python garbage collector clean them up for me so I only have 
> one, which gets cleaned when do_test returns.

You only ever have one at a time during the execution of do_test().
You have a total of 3 during your programs lifetime. (or however many
times you click the button!)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list