Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle either a list or single integer as an argument

A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.

This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:

def select_rows(to_select):     # For a list     for row in range(0, table.numRows()):         if _table.item(row, 1).text() in to_select:             table.selectRow(row)     # For a single integer     for row in range(0, table.numRows()):         if _table.item(row, 1).text() == to_select:             table.selectRow(row) 
like image 375
Steven Hepting Avatar asked Jun 15 '09 23:06

Steven Hepting


People also ask

Can I pass a list as an argument Python?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

What are the 4 types of arguments in Python?

5 Types of Arguments in Python Function Definition:positional arguments. arbitrary positional arguments. arbitrary keyword arguments.

What are the 3 types of arguments in Python?

Hence, we conclude that Python Function Arguments and its three types of arguments to functions. These are- default, keyword, and arbitrary arguments.

Can you pass a list to * args?

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.


1 Answers

Actually I agree with Andrew Hare's answer, just pass a list with a single element.

But if you really must accept a non-list, how about just turning it into a list in that case?

def select_rows(to_select):     if type(to_select) is not list: to_select = [ to_select ]      for row in range(0, table.numRows()):         if _table.item(row, 1).text() in to_select:             table.selectRow(row) 

The performance penalty for doing 'in' on a single-item list isn't likely to be high :-) But that does point out one other thing you might want to consider doing if your 'to_select' list may be long: consider casting it to a set so that lookups are more efficient.

def select_rows(to_select):     if type(to_select) is list: to_select = set( to_select )     elif type(to_select) is not set: to_select = set( [to_select] )      for row in range(0, table.numRows()):         if _table.item(row, 1).text() in to_select:             table.selectRow(row) 
like image 181
NickZoic Avatar answered Sep 22 '22 13:09

NickZoic