Created
September 8, 2014 02:58
-
-
Save dwf/62236d94f76c99f238b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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