Skip to content

Treat Parameter as Sequence

rollynoel edited this page Jun 13, 2013 · 2 revisions

Added by dholton dholton

Sometimes you may want to handle one or more items passed to a method.

Usually method overloading to handle each specific case is sufficient. But here is an example for treating a parameter as a sequence of items, even if only one item was passed

import System.Collections

def seq(x):
	if x isa IEnumerable and not x isa string:
		return x
	else:
		return (x,)

//another version using generators:
def seq2(x):
	if x isa IEnumerable and not x isa string:
		for item in x:
			yield item
	else:
		yield x

def abc (arg1, arg2, arg3):
	for item in seq(arg2):
		print item

abc(1,"test1",2)
abc(1,["test1","test2"],2)
abc(1,2,3)
abc(1,[2,3,4],5)
abc(1,(2,3,4),5)
Clone this wiki locally