473,662 Members | 2,352 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python function returns:

I am still new to Python but have used it for the last 2+ months.
One thing I'm still not used to is that functions parameters can't
change as expected. For example in C, I can have
status = get_network_inf o (strIpAddress, &strHostname , &nPortNumber )
where this fictitious function returns a status, but also returns modified
values for a hostname and a port number.
In Python, there does not seem to be an easy way to have functions return
multiple values except it can return a list such as:
strHostname, nPortNumber, status = get_network_inf o (strIpAddress,
strHostname,
nPortNumber)
Am I missing something obvious? Is there a better, or more standard way
to return values from functions?

Thanks in advance:
Michael Yanowitz
May 4 '06 #1
4 2747
Michael Yanowitz wrote:
I am still new to Python but have used it for the last 2+ months.
One thing I'm still not used to is that functions parameters can't
change as expected. For example in C, I can have
status = get_network_inf o (strIpAddress, &strHostname , &nPortNumber )
where this fictitious function returns a status, but also returns
modified
values for a hostname and a port number.
In Python, there does not seem to be an easy way to have functions
return
multiple values except it can return a list such as:
strHostname, nPortNumber, status = get_network_inf o (strIpAddress,
strHostname,
nPortNumber)
Am I missing something obvious? Is there a better, or more standard way
to return values from functions?


No, that exactly is the way to go. But usually one uses tuples and the
possibility of sequence-unpacking together to reach a solution tha at least
to my eye looks more favorable:
def foo(a, b):
return a*b, a+c

a = 10
b = 20

a, b = foo(a, b)
Diez
May 4 '06 #2
Michael Yanowitz wrote:
In Python, there does not seem to be an easy way to have functions
return
multiple values except it can return a list such as:
strHostname, nPortNumber, status = get_network_inf o (strIpAddress,
strHostname,
nPortNumber)
Am I missing something obvious? Is there a better, or more standard
way
to return values from functions?


The only obvious thing you are missing is that you don't pass in values
which are only results. Duplicating the parameters and results as you have
above would be unlikely to happen very much in practice.

Oh, and it doesn't return a list, it actually returns a tuple but it is
easiest just to think of your function as just returning three results.

Returning additional results is better than rebinding parameters because it
makes it really clear at the point of calling which variables are
parameters and which are results.

The other not very pythonic thing about your example is that it returns a
status code: Python largely tends towards using exceptions rather than
status codes, so if in C you had:

switch ((status=get_ne twork_info(addr , &host, &port)) {
case S_OK:
break;
case ERROR_1:
... handle error ...
break;
case default:
... handle other errors ...
};

In Python you would have something like:

try:
host, port = get_network_inf o(addr)
except ERROR_1:
... handle error ...
except:
... handle other errors ...

which means you can handle the error either right next to the call or at
some outer level (you don't have to manually propogate your status), you
can't accidentally forget to check the status code, and the actual call is
much simpler and clearer (especially if the error is handled at some outer
level).
May 4 '06 #3
Michael Yanowitz wrote:
I am still new to Python but have used it for the last 2+ months.
One thing I'm still not used to is that functions parameters can't
change as expected.

For example in C, I can have
status = get_network_inf o (strIpAddress, &strHostname , &nPortNumber )
You have to understand that Python and C are totally different beasts.

A C variable is mostly symbolic name for a memory address, tagged with
type infos. Assigning to a variable means storing a value at this
address. Reading a variable means retrieving whatever value is stored at
this memory address.

Python does not in fact have a concept of "variables" . It has names and
objects. A binding is the association (in a hash table) of a symbolic
name (which is nothing more than a name) and a reference (read:
something like a smart pointer) to an object (which is itself a complex
data structure). So-called "assignemen t" (correct term is "binding")
'binds' together a name and a reference to an object. Except for some
special cases (mainly objects - which are they're own namespaces - and
when using the 'global' statement), this creates an entry in the current
namespace. Also, rebinding a name has no effect on other names bound to
the same object.

Function's params are bindings in the function's local namespace. This
means that the params *names* are local to the function. So rebinding a
param in a function won't have no effect on bindings in the caller's
namespace.

*But* - since many names can refer to the same object - *modifying* the
object referenced by a name will, well, modify this object, so this
modification will be visible everywhere.

ie (dummy example):

def appendToList(al ist, what):
alist.append(wh at)

mylist = []
appendToList(my list, 42)
print mylist

What doesn't work as you'd expect is:

def failsToHaveSide Effects(alist, anything):
print "before rebinding : alist = ", alist, " - anything = ", anything
alist = anything
print "after rebinding: alist = ", alist

mylist = []
print "before function call, mylist = ", mylist
failsToHaveSide Effects(mylist, 42)
print "after function call, mylist = ", mylist
So as you can see, it's quite possible for a function to *modify* it's
params - it's just rebindings of params that won't have side effects
outside the function's namespace.

Now, there is the case of immutable types (int, strings, tuples, ....).
As implied, one cannot modify objects of these types - just create them.
So in order to have a function that "change the value" of an immutable
object, you have to wrap it into a mutable object, ie:

def getAnswer(alist ):
alist[0] = "42"

answer = ["answer is ?"]
getAnswer(answe r)
print "answer is : ", answer[0]

(snip)
In Python, there does not seem to be an easy way to have functions return
multiple values except it can return a list such as:
strHostname, nPortNumber, status = get_network_inf o (strIpAddress,
strHostname,
nPortNumber)
Am I missing something obvious? Is there a better, or more standard way
to return values from functions?


This *is* the 'standard' (ie: idiomatic) way to return multiple values
from a function. The C idiom of passing pointers to variables that are
to be modified comes from C's limitations, namely no exception handling
and only one return value[1], which leads to using the return value as a
status report and relying on side effect for useful values.

[1] To be pedantic, Python only allows one return value too - but this
value can be a tuple or list, and then one can take advantage of
tuple/list expansions that allows multiple assignment...

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 4 '06 #4
Michael Yanowitz <m.********@kea rfott.com> wrote:
In Python, there does not seem to be an easy way to have functions return
multiple values except it can return a list such as:
strHostname, nPortNumber, status = get_network_inf o (strIpAddress,
strHostname,
nPortNumber)
Am I missing something obvious? Is there a better, or more standard way
to return values from functions?


I'm kind of repeating what other people have said, but there
isn't a better way. Not just in Python, but in any language.
If your function is returning multiple values, why should you
have to split them into one privileged "return value" plus a
bunch of Out (or InOut) parameters? That's a historical mis-
feature of older languages, and one which more newer languages
would do well to fix.

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu become se bera eadward ofdun hlddre heafdes bce bump bump bump
May 4 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

63
5141
by: Davor | last post by:
Is it possible to write purely procedural code in Python, or the OO constructs in both language and supporting libraries have got so embedded that it's impossible to avoid them? Also, is anyone aware of any scripting language that could be considered as "Python minus OO stuff"? (As you can see I'm completely new to Python and initially believed it's a nice&simple scripting language before seeing all this OO stuff that was added in over...
32
2518
by: David | last post by:
Hi I'm trying to teach myself python and so far to good, but I'm having a bit of trouble getting a function to work the way I think it should work. Right now I'm taking a simple program I wrote in Fortran and trying to do it in Python. I got it to work, but now I'm trying to modularize it. My fortran program uses a subroutine and I was trying to do the same thing in Python. But I'm still new so I'm having trouble understanding what I'm...
1
1587
by: David | last post by:
I have this error message poping up when I try to import a module I made in C using the Python/C API. Everything compiles like a charm. Gives me this error message : Traceback (most recent call last): File "mod_test.py", line 4, in ? import utm ImportError: dynamic module does not define init function (initutm)
20
4054
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort” method. For example: li=;
14
2724
by: Java and Swing | last post by:
static PyObject *wrap_doStuff(PyObject *self, PyObject *args) { // this will store the result in a Python object PyObject *finalResult; // get arguments from Python char *result = 0; char *in= 0; char *aString = 0; char *bString = 0; MY_NUM *a;
0
2257
by: Xah Lee | last post by:
One-Liner Loop in Functional Style Xah Lee, 200510 Today we show a example of a loop done as a one-liner of Functional Programing style. Suppose you have a list of file full paths of images: /Users/t/t4/oh/DSCN2059m-s.jpg
15
2343
by: Claudio Grondi | last post by:
Let's consider a test source code given at the very end of this posting. The question is if Python allows somehow access to the bytes of the representation of a long integer or integer in computers memory? Or does Python hide such implementation details that deep, that there is no way to get down to them? The test code below shows, that extracting bits from an integer value n is faster when using n&0x01 than when using n%2 and I...
0
1976
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 385 open (+21) / 3790 closed (+21) / 4175 total (+42) Bugs : 1029 open (+43) / 6744 closed (+43) / 7773 total (+86) RFE : 262 open ( +4) / 291 closed ( +4) / 553 total ( +8) New / Reopened Patches ______________________
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8343
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8762
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1992
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.