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>A function should do one thing, and do that one thing well. In the case of <code>data_writer</code>, its one thing is to write data to a file-like object. Let the caller worry about providing such an object. That said, you can also provide that caller in the form of a wrapper that takes a file name and opens it for <code>data_writer</code>.</p>

<pre><code>def data_writer(data, file_obj):
    spiffy_data = data # ...
    file_obj.write(spiffy_data)

def write_data_to_file(data, file_name):
    with open(file_name, "w") as f:
        data_writer(f, file_name)
</code></pre>

python python-3.x