Duck prints trouble. Duck typing test for "i-am-like-a-list"

USE CONTEXT ADDED AT THE END

I often want to work with an abstract object like a list. eg.

def list_ish(thing):
    for i in xrange(0,len(thing)):
        print thing[i]

Now this is suitable if the thing is a list, but will fail if it is a thing, for example, a dict. what is pythonic, why ask: "Are you acting like a list?"

Note:

hasattr('__getitem__') and not hasattr('keys')

this will work for all cases that I can think of, but I don’t like to determine the type of duck negatively, since I expect that there may be cases that it does not catch.

Actually I want to ask. "Hey, you work on the whole record in how I expect the list to be?" eg.

  thing[i],  thing[4:7] = [...],   etc.

. try/except, . , .

- " " - , , , dict-like, . - "" - , , -

- , , .

- , , , "-", -, - - , .

- , , , , , , .

- , 'is_matrix' 'is_point_list' , . , , .

- , , , , , python.

, , , , , , Pythonista​​p >

kool-...

+4
3

, , list dict, :

try:
    thing[:0]
except TypeError:
    # probably not list-like
else:
    # probably list-like

dict, .

, str unicode , , . , , , __delitem__ __setitem__:

def supports_slices_and_editing(thing):
    if hasattr(thing, '__setitem__') and hasattr(thing, '__delitem__'):
        try:
            thing[:0]
            return True
        except TypeError:
            pass
    return False

, , , , , . list dict s, isinstance, ? , , , - , . .

+3

. collections.Sequence collections.MutableSequence:

if isinstance(your_thing, collections.Sequence):
    # access your_thing as a list

Python ( ) 2.6.

your_thing, ( ). , , , .

, . , , , . , list_ish __len__ __getitem__, , . __getitem__ (, dict) .

+1

, , "" , python, , :

def is_list_like(thing):
    return hasattr(thing, '__setslice__')

def is_dict_like(thing):
    return hasattr(thing, 'keys')

, , :

  • (1) dict-thing, - .
  • (2) python
  • (3) will return the correct answer if someone implements a "complete" set of basic methods for the / dict list
  • (4) fast (ideally does not select objects during the test)

EDIT: Consolidated Ideas by @DanGetz

+1
source

Source: https://habr.com/ru/post/1588898/


All Articles