0

I'm trying to parse a tuple of the form:

a=(1,2)

or

b=((1,2), (3,4)...)

where for a's case the code would be:

x, y = a

and b would be:

for element in b:
    x, y = element

is there an fast and clean way to accept both forms? This is in a MIDI receive callback (x is a pointer to a function to run, and y is intensity data to be passed to a light).

1
  • The right way to do this is to always accept the same level of nesting. So, never a = (1, 2), always a = [(1, 2),]. Tarantula is getting downvoted because this doesn't answer your question, but that doesn't change its correctness, albeit it doesn't seem he meant to point that out :). Commented Aug 19, 2012 at 4:21

2 Answers 2

2
# If your input is in in_seq...
if hasattr(in_seq[0], "__iter__"):
    # b case
else:
    # a case

This basically checks to see if the first element of the input sequence is iterable. If it is, then it's your second case (since a tuple is iterable), if it's not, then it's your first case.

If you know for sure that the inputs will be tuples, then you could use this instead:

if isinstance(in_seq[0], tuple):
    # b case
else:
    # a case

Depending on what you want to do, your handling for the 'a' case could be as simple as bundling the single tuple inside a larger tuple and then calling the same code on it as the 'b' case, e.g...

b_case = (a_case,)

Edit: as pointed out in the comments, a better version might be...

from collections import Iterable
if isinstance(in_seq[0], Iterable):
    # ...
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Amber, I can't vote you up because it requires >= 15 reputation. I'm playing with hasattr now...
It is bad advice to check for __iter__. Use collections.Iterable.
It's bad advice to use either.
What is the reason to use collections? The data is pretty sanitized by the time I'm parsing it. Are there any performance issues?
1

The right way to do that would be:

a = ((1,2),) # note the difference
b = ((1,2), (3,4), ...)

for pointer, intensity in a:
   pass # here you do what you want

4 Comments

I think the question is how to accept a=(1,2), not a=((1,2),).
I tried that, but it doesn't seem to pass through functions, 'def fn(val) <CR> return val <CR> returns (1,2) if i pass it (1,2), --- this is my first question, how do a <CR> in this reply without posting?
@Bill: what you mean by "pass through functions" ?
You'll need to elaborate a little more on your original question, what did you supposed that a function: 'def fn(val): return val' would return with the parameter '(1,2)' ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.