Skip to content

Instantly share code, notes, and snippets.

@dwf
Created September 8, 2014 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwf/62236d94f76c99f238b5 to your computer and use it in GitHub Desktop.
Save dwf/62236d94f76c99f238b5 to your computer and use it in GitHub Desktop.
from functools import wraps
import sys
# Goddamnit Python 2/3 differences.
str_type = str if sys.version_info[0] >= '3' else basestring
def filename_or_file_like(mode):
"""Decorator that checks if the first argument to a function is
an instance of a string type, and opens it with the specified mode
before calling the function.
Example
-------
@filename_or_file_like('rb')
def func_that_reads_something(f, a, b, c):
s = f.read()
return s
"""
def wrapper_factory(fn):
@wraps
def wrapper(f, *args, **kwargs):
# Open if it's a string
if isinstance(f, str_type):
with open(f, mode) as open_f:
return fn(open_f, *args, **kwargs)
else:
# Assume it's file-like
return fn(f, *args, **kwargs)
return wrapper
return wrapper_factory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment