How can I tell if I have a file-like object?
<p>I want to have a function that writes data to a file:</p>

<pre><code>def data_writer(data, file_name):
    spiffy_data = data # ...
    with open(file_name, 'w') as out:
        out.write(spiffy_data)
</code></pre>

<p>But sometimes, I have a file object instead of a file name. In this case, I sometimes have a <code>tempfile.TemporaryFile</code> (which creates a file-like object that's writable).</p>

<p>I'd like to be able to write something like:</p>

<pre><code>def data_writer(data, file_thing):
    spiffy_data = data # ...
    if type(file_thing) is file_like:
        file_thing.write(spiffy_data)
    else:
        with open(file_name, 'w') as out:
            out.write(spiffy_data)
</code></pre>

<p>What's a good way to do this?</p>

<p>Also, does makes sense to do in Python?</p>

<p>While your approach is <a href="https://docs.python.org/3/glossary.html#term-lbyl" rel="nofollow"><code>LBYL</code></a>, it's pythonic to assume it's <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow"><code>EAFP</code></a>. So you could just <code>try</code> to </p>

<ul>
<li><code>write()</code> to the <code>file_thing</code> you received or</li>
<li><code>open()</code> it</li>
</ul>

<p>and <code>except</code> a potential exception, depending on which you feel better represents the default case.</p>

<p><strong>Edit:</strong> Cf <a href="http://stackoverflow.com/questions/40110731/how-can-i-tell-if-i-have-a-file-like-object/40110875#comment67493524_40110875">ShadowRanger's comment</a> for why mixing the exception handling with a context manager is rather unelegant here.</p>

python python-3.x