Check if object is file-like in Python

后端 未结 8 774
抹茶落季
抹茶落季 2020-12-01 00:02

File-like objects are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of

相关标签:
8条回答
  • 2020-12-01 00:33

    As others have said you should generally avoid such checks. One exception is when the object might legitimately be different types and you want different behaviour depending on the type. The EAFP method doesn't always work here as an object could look like more than one type of duck!

    For example an initialiser could take a file, string or instance of its own class. You might then have code like:

    class A(object):
        def __init__(self, f):
            if isinstance(f, A):
                # Just make a copy.
            elif isinstance(f, file):
                # initialise from the file
            else:
                # treat f as a string
    

    Using EAFP here could cause all sorts of subtle problems as each initialisation path gets partially run before throwing an exception. Essentially this construction mimics function overloading and so isn't very Pythonic, but it can be useful if used with care.

    As a side note, you can't do the file check in the same way in Python 3. You'll need something like isinstance(f, io.IOBase) instead.

    0 讨论(0)
  • 2020-12-01 00:34

    You can try and call the method then catch the exception:

    try:
        fp.read()
    except AttributeError:
        raise something
    

    If you only want a read and a write method you could do this:

    if not (hasattr(fp, 'read') and hasattr(fp, 'write')):
       raise something
    

    If I were you I would go with the try/except method.

    0 讨论(0)
提交回复
热议问题