On Thu, Feb 21, 2008 at 3:37 PM, Matt Wilson <[EMAIL PROTECTED]> wrote:
>
> I have code like this in a lot of controllers:
>
> def f(a, b):
>
> # Make sure that a is a list.
> if not isinstance(a, list):
> a = [a]
>
>
> for x in a:
> ....
>
> I have to make sure that a is a list, not a string, before I iterate
> over it.
>
> This is another common pattern:
>
> def g(**kwargs):
> a = kwargs.get('a', [])
> if not isinstance(a, list):
> a = [a]
>
> It's roughly the same thing, but a is potentially a key in kwargs.
>
> Is there some way to clean this code up?
Yeaph... put one of these 2 functions in your utils library:
def custom_ensure_sequence(obj):
"""Adapted from turbogears.util.ensure_sequence"""
if obj is None:
return []
elif isSequenceType(obj) and not isinstance(obj, basestring):
return obj
else:
return [obj]
def ensure_list(obj):
"""Same thing, but returns a list... always"""
if obj is None:
return []
elif isSequenceType(obj) and not isinstance(obj, basestring):
return list(obj)
else:
return [obj]
The first one would return a tuple, if one is provided.. .the second one
will turn it in a list.
Cheers,
Roger
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---