473,714 Members | 2,562 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

determining the number of output arguments

Hello,

def test(data):

i = ? This is the line I have trouble with

if i==1: return data
else: return data[:i]

a,b,c,d = test([1,2,3,4])

How can I set i based on the number of output arguments defined in
(a,b,c,d)?

Thank you,
Darren
Jul 18 '05 #1
66 5007
On Sun, 14 Nov 2004 17:12:24 -0500, Darren Dale <dd**@cornell.e du>
declaimed the following in comp.lang.pytho n:
Hello,

def test(data):

i = ? This is the line I have trouble with

if i==1: return data
else: return data[:i]

a,b,c,d = test([1,2,3,4])

How can I set i based on the number of output arguments defined in
(a,b,c,d)?

This is rather confusing...

What do you expect to receive for

a,b,c,d = test([1,2,3,4,5])

Note, you are only passing ONE argument into the function, and
apparently wanting a tuple in return...

Problem: in the case of mismatched lengths (4 items in
destination, and 5 in the list) you get an exception. Otherwise you
could just use

a,b,c,d = tuple([1,2,3,4])
If you are actually trying to work with an unknown number of
input arguments (rather than a single argument of a list)...
def test(*data): .... print len(data)
.... test([1,2,3,4]) 1 test(1,2,3,4) 4
def test(*data): .... return data
.... test([1,2,3,4]) ([1, 2, 3, 4],) test(1,2,3,4) (1, 2, 3, 4) def test(*data): .... return list(data)
.... test([1,2,3,4]) [[1, 2, 3, 4]] test(1,2,3,4) [1, 2, 3, 4]

Thank you,
Darren
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Jul 18 '05 #2
Darren Dale wrote:
Hello,

def test(data):

i = ? This is the line I have trouble with

if i==1: return data
else: return data[:i]

a,b,c,d = test([1,2,3,4])

How can I set i based on the number of output arguments defined in
(a,b,c,d)?


Something like this:

def test(*args, **kwargs):
i = len(args) + len(kwargs)

should work. But note that the usage example you gave will result in i
having a value of 1 -- you're passing in a single argument (which is a
list).

Of course, if you're always going to be passing a sequence into your
function, and you want to get the length of that sequence, then it's
pretty simple:

def test(data):
i = len(data)
return data[:i]

Note, however, that this function is effectively a no-op as it stands.
Presumably you're intending to do something to transform data, which may
change its length? Otherwise, it would be simpler to just modify the
list (or a copy of it) in-place in a for loop / list comp, and not worry
about the length at all.

Jeff Shannon
Technician/Programmer
Credit International
Jul 18 '05 #3
Fernando Perez <fp*******@yaho o.com> wrote:
suspect that by playing very nasty tricks with sys._getframe() , the dis
and the inspect modules, you probably _could_ get to this information, at
least if the caller is NOT a C extension module. But I'm not even 100%
sure this works, and it would most certainly the kind of black magic I'm
sure you are not asking about. But given the level of expertise here, I
better cover my ass ;-)


Yep, that's the cookbook recipe Jp was mentioning -- Sami Hangaslammi's
recipe 284742, to be precise. Yep, it _is_ going into the printed 2nd
edition (which I'm supposed to be working on right now -- deadline
closing in, help, help!-).
Alex
Jul 18 '05 #4
Alex Martelli wrote:
Fernando Perez <fp*******@yaho o.com> wrote:
suspect that by playing very nasty tricks with sys._getframe() , the dis
and the inspect modules, you probably _could_ get to this information, at
least if the caller is NOT a C extension module. But I'm not even 100%
sure this works, and it would most certainly the kind of black magic I'm
sure you are not asking about. But given the level of expertise here, I
better cover my ass ;-)


Yep, that's the cookbook recipe Jp was mentioning -- Sami Hangaslammi's
recipe 284742, to be precise. Yep, it _is_ going into the printed 2nd
edition (which I'm supposed to be working on right now -- deadline
closing in, help, help!-).


Well, I feel pretty good now: I didn't see Jp's mention of this, and just
guessed it should be doable with those three tools. I just looked it up, and
it seems it's exactly what I had in mind :) Cute hack, but I tend to agree
with Scott Daniels' comment that this kind of cleverness tends to promote
rather unreadable code. Maybe I just haven't seen a good use for it, but I
think I'd rather stick with more explicit mechanisms than this.

Anyway, is it true that this will only work for non-extension code? If you are
being called from a C extension, dis & friends are toast, no?

Cheers,

f

Jul 18 '05 #5
Fernando Perez <fp*******@yaho o.com> wrote:
Yep, that's the cookbook recipe Jp was mentioning -- Sami Hangaslammi's
recipe 284742, to be precise. Yep, it _is_ going into the printed 2nd
edition (which I'm supposed to be working on right now -- deadline
closing in, help, help!-).
Well, I feel pretty good now: I didn't see Jp's mention of this, and just
guessed it should be doable with those three tools. I just looked it up, and
it seems it's exactly what I had in mind :) Cute hack, but I tend to agree
with Scott Daniels' comment that this kind of cleverness tends to promote
rather unreadable code. Maybe I just haven't seen a good use for it, but I
think I'd rather stick with more explicit mechanisms than this.


Yeah, but "once and only once" is a great principle of programming. Any
time you have to say something _TWICE_ there's something wrong going on.

So,

a, b, c, d = lotsa[:4]

_should_ properly give the impression of a code smell, if your "once and
only once" sense is finely tuned. What's the business of that ':4' on
the RHS? Showing the compiler that you can count correctly?! You're
having to tell twice that you're getting four items into separate
variables, once by listing exactly four variables on the LHS, and
another time by that ':4' on the RHS. IMHO, that's just as bogus as
struct.unpack's limitation of not having any way to indicate explicitly
'and all the rest of the bytes goes here', and for similar reasons.

I think it would be better to have a way to say 'and all the rest'.
Lacking that, some automated way to count how many items are being
unpacked on the LHS is probably second-best.
Anyway, is it true that this will only work for non-extension code? If
you are being called from a C extension, dis & friends are toast, no?


Yep, whenever your function isn't being called as the only item on the
RHS of a multiple assignment, then counting how many items are on the
LHS are being unpacked in that inexistent or unapplicable multiple
assignment is right out. Presumably, any way to count the number of
items in this fashion will need a way to indicate "not applicable",
though it's not obvious whether raising an exception, or returning a
clearly bogus value such as 0, is most useful.

Another case where a specific number of items is requested, which is not
(syntactically speaking) a multiple assignment, is assignment to an
_extended_ slice of, e.g., a list (only; assignment to a slice with a
stride of 1 is happy with getting whatever number of items are coming).
I don't particularly LIKE writing:
L[x:y:z] = len(L[x:y:z]) * [foo]
i.e. having to extract the extended slice first, on the RHS, just to
gauge how many times I must repeat foo. However, if I squint in just
the right way, I _can_ try to convince myself that this _isn't_ really
violating "once and only once"... and I do understand how hard it would
be to allow a 'how many items are needed' function to cover this
case:-(.
Alex
Jul 18 '05 #6

al*****@yahoo.c om (Alex Martelli) wrote:

Fernando Perez <fp*******@yaho o.com> wrote:
Yep, that's the cookbook recipe Jp was mentioning -- Sami Hangaslammi's
recipe 284742, to be precise. Yep, it _is_ going into the printed 2nd
edition (which I'm supposed to be working on right now -- deadline
closing in, help, help!-).
Well, I feel pretty good now: I didn't see Jp's mention of this, and just
guessed it should be doable with those three tools. I just looked it up, and
it seems it's exactly what I had in mind :) Cute hack, but I tend to agree
with Scott Daniels' comment that this kind of cleverness tends to promote
rather unreadable code. Maybe I just haven't seen a good use for it, but I
think I'd rather stick with more explicit mechanisms than this.


Yeah, but "once and only once" is a great principle of programming. Any
time you have to say something _TWICE_ there's something wrong going on.

So,

a, b, c, d = lotsa[:4]

_should_ properly give the impression of a code smell, if your "once and
only once" sense is finely tuned. What's the business of that ':4' on
the RHS? Showing the compiler that you can count correctly?! You're
having to tell twice that you're getting four items into separate
variables, once by listing exactly four variables on the LHS, and
another time by that ':4' on the RHS. IMHO, that's just as bogus as
struct.unpack's limitation of not having any way to indicate explicitly
'and all the rest of the bytes goes here', and for similar reasons.


The slicing on the right is not so much to show the compiler that you
know how to count, it is to show the runtime that you are looking for
a specified slice of lotsa. How would you like the following two cases
to be handled by your desired Python, and how would that make more sense
than what is done now?

a,b,c = [1,2,3,4]
a,b,c = [1,2]

I think it would be better to have a way to say 'and all the rest'.
Lacking that, some automated way to count how many items are being
unpacked on the LHS is probably second-best.
Is it worth a keyword, or would a sys.getframe()/bytecode hack be
sufficient? In the latter case, I'm sure you could come up with such a
mechanism, and when done, maybe you want to offer it up as a recipe in
the cookbook *wink*.

Another case where a specific number of items is requested, which is not
(syntactically speaking) a multiple assignment, is assignment to an
_extended_ slice of, e.g., a list (only; assignment to a slice with a
stride of 1 is happy with getting whatever number of items are coming).
I don't particularly LIKE writing:
L[x:y:z] = len(L[x:y:z]) * [foo]

I much prefer...

for i in xrange(x, y, z):
L[i] = foo

But then again, I don't much like extended list slicing (I generally
only use the L[:y], L[x:] and L[x:y] versions).

- Josiah

Jul 18 '05 #7
On Mon, 15 Nov 2004 19:44:06 -0800, Josiah Carlson wrote:
I think it would be better to have a way to say 'and all the rest'.
Lacking that, some automated way to count how many items are being
unpacked on the LHS is probably second-best.


Is it worth a keyword, or would a sys.getframe()/bytecode hack be
sufficient?


Who needs a keyword?

a, b, *c = [1, 2, 3, 4]
a, b, *c = [1, 2]

In the latter case I'd expect c to be the empty tuple.

Clear parallels to function syntax:
def f(a, b, *c): .... print c
.... f(1, 2, 3, 4) (3, 4) f(1, 2)

()

No parallel for **, but... *shrug* who cares?
Jul 18 '05 #8
Josiah Carlson <jc******@uci.e du> wrote:
a, b, c, d = lotsa[:4]

_should_ properly give the impression of a code smell, if your "once and
only once" sense is finely tuned. What's the business of that ':4' on
the RHS? Showing the compiler that you can count correctly?! You're ...
The slicing on the right is not so much to show the compiler that you
know how to count, it is to show the runtime that you are looking for
a specified slice of lotsa. How would you like the following two cases
to be handled by your desired Python, and how would that make more sense
than what is done now?

a,b,c = [1,2,3,4]
a,b,c = [1,2]
I would like to get exceptions in these cases, which, being exactly what
IS done now, makes exactly as much sense as itself. Note that there is
no indicator in either of these forms that non-rigid unpacking is
desired. Assuming the indicator for 'and all the rest' were a prefix
star, then:

a, b, *c = [1, 2, 3, 4]
a, b, *c = [1, 2]

should both set a to 1, b to 2, and c respectively to [3, 4] and []. Of
course there would still be failing cases:

a, b, *c = [1]

this should still raise -- 'a, b, *c' needs at least 2 items to unpack.

I think it would be better to have a way to say 'and all the rest'.
Lacking that, some automated way to count how many items are being
unpacked on the LHS is probably second-best.


Is it worth a keyword, or would a sys.getframe()/bytecode hack be
sufficient? In the latter case, I'm sure you could come up with such a
mechanism, and when done, maybe you want to offer it up as a recipe in
the cookbook *wink*.


Two recipes in the 2nd ed of the CB can be combined to that effect
(well, nearly; c becomes an _iterator_ over 'all the rest'), one by
Brett Cannon and one by Sami Hangaslammi. Not nearly as neat and clean
as if the language did it, of course.

Another case where a specific number of items is requested, which is not
(syntactically speaking) a multiple assignment, is assignment to an
_extended_ slice of, e.g., a list (only; assignment to a slice with a
stride of 1 is happy with getting whatever number of items are coming).
I don't particularly LIKE writing:
L[x:y:z] = len(L[x:y:z]) * [foo]


I much prefer...

for i in xrange(x, y, z):
L[i] = foo


Not the same semantics, in the general case. For example:

L[1:-1:2] = ...

rebinds (len(L)/2)-1 items; your version rebinds no items, since
xrange(1, -1, 2) is empty. To simulate the effect that assigning to an
extended slice has, you have to take a very different tack:

for i in slice(x, y, z).indices(len( L)):
L[i] = foo

and that's still quite a bit less terse and elegant, as is usually the
case for fussy index-based looping whenever it's decently avoidable.
But then again, I don't much like extended list slicing (I generally
only use the L[:y], L[x:] and L[x:y] versions).


It may be that in your specific line of work there is no opportunity or
usefulness for the stride argument. Statistically, however, it's
somewhat more likely that you're not taking advantage of the
opportunities because, given your dislike, you don't even notice them --
as opposed to the opportunities not existing at all, or you noticing
them, evaluating them against the lower-level index-based-looping
alternatives, and selecting the latter. If you think that extended
slices are sort of equivalent to xrange, as above shown, for example,
it's not surprising that you're missing their actual use cases.
Alex
Jul 18 '05 #9

Jeremy Bowers <je**@jerf.or g> wrote:

On Mon, 15 Nov 2004 19:44:06 -0800, Josiah Carlson wrote:
I think it would be better to have a way to say 'and all the rest'.
Lacking that, some automated way to count how many items are being
unpacked on the LHS is probably second-best.
Is it worth a keyword, or would a sys.getframe()/bytecode hack be
sufficient?


Who needs a keyword?

a, b, *c = [1, 2, 3, 4]
a, b, *c = [1, 2]

I'll post the same thing that was posted by James Knight on python-dev
about this precise syntax...
James Knight wrote: Two threads on the topic, with rejections by Guido:
http://mail.python.org/pipermail/pyt...er/030349.html
http://mail.python.org/pipermail/pyt...st/046684.html

Guido's rejection from
http://mail.python.org/pipermail/pyt...t/046794.html:
For the record, let me just say that I'm -1 on adding this feature
now. It's only a minor convenience while it's a fairly big change to
the parser and code generator, but most of all, Python's growth needs
to be reduced. If we were to add every "nice" feature that was
invented (or present in other languages), Python would lose one of its
main charms, which is that it is really a rather simple language that
can be learned and put to production quickly.

So while I appreciate the idea (which BTW has been proposed before) I
think it's not worth adding now, and if you don't hear from me again
on this topic it's because I haven't changed my mind...

Guido hasn't updated his stance, so don't hold your breath.

- Josiah

Jul 18 '05 #10

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

Similar topics

5
1994
by: Elaine Jackson | last post by:
Suppose one of the arguments of a function f_1 is another function f_2. Can f_1 access the number of arguments taken by f_2? (I'm writing a little script to automate the construction of logical truth-tables.) Thanks. Peace
8
2534
by: Mark English | last post by:
I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window would be returned an instance of the class. The actual application I'm interested in writing would either have simple type attributes (int, string, etc.), or attributes using types already defined in a c-extension, although I'd prefer not to...
2
1280
by: William Payne | last post by:
Hello, I am making a very simple and crude Makefile generator, that currently supports three different options: --project-name=<name_of_project> --source-files=<source_file_names_separated_by_commas> --resource-file=<name_of_resource_file_if_any> The first thing I do is to put all program arguments (excluding argv) in a std::vector of std::strings. Then I call a function to determine which options were passed to the program and their...
3
1742
by: Trevor M. Lango | last post by:
The number of arguments passed to the following functions can be determined - but how is this coded? main (int argc, char *argv) printf ( string format ) I would like to be able to write arbitrary functions that know how many arguments were passed to them.
5
2992
by: Lyn | last post by:
Is there any way of determining in VBA the name and arguments of the currently executed procedure? To assist in debugging, I would like to be able to trace the procedures as they are executed. Then, when it crashes with Access's usual unhelpful error messages, at least I will be able to determine in which procedure it happened. What I had in mind was something like this, inserted as the first statement in every procedure during...
4
13570
by: Augustus S.F.X Van Dusen | last post by:
I have recently come across the following construction: #define P_VAR(output, string, args...) \ fprintf (output, "This is "string"\n", ##args) which can be invoked as follows: int x = 1, y = 2 ; char * str = "String" ;
18
1913
by: Lie | last post by:
I'm very surprised actually, to see that Python rejected the use of fractional/rational numbers. However, when I read the PEP, I know exactly why the proposal was rejected: People compared fractions with integers, while it should be more fairly compared to floats. Arguments against: - When I use the result of / as a sequence index, it's usually an error which should not be hidden by making the program working for some data, since it...
53
4950
by: Aaron Gray | last post by:
Due to M$'s stupidity in not making DOMElements first class citizens the following will not work :- function isElement( o) { return o instanceof Element } It works for FF, Opera and Safari.
0
9307
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9170
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
9071
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
9009
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
7946
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5943
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
4462
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
4715
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2514
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.