Andy Dingley wrote: > I seem to be writing the following fragment an awful lot, and I'm sure > it's not the best and Pythonic way to do things. Any advice on better > coding style? > > pluginVersionNeeded is a parameter passed into a method and it can > either be a simple scalar variable, or it can be a list of the same > variables. My problem is how to iterate it, whether it's a a list or > not. > > I can't simply throw it into the for...in loop -- if the scalar > variable were to be a string (which is considered to be atomic in my > application) then Python sees this string as iterable and iterates over > the characters in it! > > > versionsNeeded = pluginVersionNeeded > if isinstance( versionsNeeded, list): > versionsToTest = versionsNeeded > else: > versionsToTest = [ versionsNeeded ] > for versionNeeded in versionsToTest: > pass
Use a function. def listify(v): if not isinstance(v, list): return [v] return v versionsToTest = listify(versionsNeeded) Diez -- http://mail.python.org/mailman/listinfo/python-list