HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Finding an item name starting or ending with from a list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemstartingfromwithnamefindinglistending

Problem

I have written this helper function. I want to know if there is an even better approach, considering that I do not want to add a dependency to any additional module.

def _isobjectInList(lst, name, criteria='startswith'):
    """ Find item in the list  starting or ending with name passed.

        :param lst: list of items/ objects
        :type lst: list

        :param name: name starting or ending with.
        :param name: string

        :param criteria: function of string obect whether startswith or endswith
        :param criteria: built-in method of str object 
    """
    return [itemfound for itemfound in lst if getattr(itemfound, criteria)(name)]

Solution

Use first class functions, not hardcoded strings:

def _isobjectInList(lst, name, criteria=str.startswith):
    """
    >>> _isobjectInList(['foobaz','null'],'foo')
    ['foobaz']
    """
    return [i for i in lst if criteria(i, name)]


also give it a better name

Code Snippets

def _isobjectInList(lst, name, criteria=str.startswith):
    """
    >>> _isobjectInList(['foobaz','null'],'foo')
    ['foobaz']
    """
    return [i for i in lst if criteria(i, name)]

Context

StackExchange Code Review Q#92230, answer score: 3

Revisions (0)

No revisions yet.