[Tutor] passing results between functions

Alan Gauld alan.gauld at btinternet.com
Wed Apr 25 20:12:22 CEST 2012


On 25/04/12 10:36, Gerhardus Geldenhuis wrote:
> Hi
> I wrote two functions which does different manipulations on text files.
>
> To start out with I passed the filename as a parameter and each function
> opened the file and saved it.

I assume you mean it did some processing on the file data and then wrote 
it back?

> I then realized I would need to do that twice if I wanted to use both my
> functions on the same file. I the modified the functions to take the
> input as follows:
> myfunction(open(sys.argv[1]),'ro'))

You mean it took a file object and a string?

> It still wasn't good enough so I modified the function to return data as
> follows:
>
> def myfunction
> returndata = []
> # some code
> ...
>    return ''.join(returndata)

So it returns a string.

> so now I can do myfunction(mysecondfunction(sys.argv[1],'ro'))
> or mysecondfunction(myfunction(sys.argv[1],'ro'))

Thats inconsistent since to one occasion you pass two arguments but on 
the other only one - the return value of the first function. And since 
the first parameter is expecting a file object the string will cause an 
error.

But if you fixed the inconsistent data issue then the principle is fine.

> so my question is philosophical. Is that the pythonian way or is there a
> better/easier/more efficient way to pass data?

It depends what kind of data and what you mean by "pass".
You could use objects to pass more complex types of data, or tuples to 
pass multiple values. Or you could write the values into a shared 
database. It just depends on what you want to do, whether the function 
needs to e thread-safe, how big the data is, etc.

> To be honest I am still a bit stuck in how I did things when I
> programmed in Delphi years ago and trying to make the paradigm shift and
> understanding the data structures.

Thee is virtually no difference between Delphi and Python in the way 
functions (and objects) work. I'm not sure what paradigmn shift you have 
in mind. Delphi can't return tuples, but other than that the options and 
styles are pretty similar.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list