1# Created By: Virgil Dupras 2# Created On: 2010-12-20 3# Copyright 2010 Hardcoded Software (http://www.hardcoded.net) 4# 5# This software is licensed under the "BSD" License as described in the "LICENSE" file, 6# which should be included with this package. The terms are also available at 7# http://www.hardcoded.net/licenses/bsd_license 8 9 10def open_if_filename(file_or_path, mode='rb'): 11 """ 12 file_or_path can be either a string or a file-like object. 13 if it is a string, a file will be opened with mode. 14 Returns a tuple (file, should_be_closed). 15 """ 16 if isinstance(file_or_path, str): 17 return (open(file_or_path, mode), True) 18 else: 19 return (file_or_path, False) 20 21 22class FileOrPath: 23 def __init__(self, file_or_path, mode='rb'): 24 self.file_or_path = file_or_path 25 self.mode = mode 26 self.mustclose = False 27 self.fp = None 28 29 def __enter__(self): 30 self.fp, self.mustclose = open_if_filename(self.file_or_path, self.mode) 31 return self.fp 32 33 def __exit__(self, exc_type, exc_value, traceback): 34 if self.fp and self.mustclose: 35 self.fp.close() 36 37 38def cond(condition, true_value, false_value): 39 """Return true_value if condition is true, and false_value otherwise. 40 41 :param bool condition: The condition to evaluate. 42 :param true_value: Value to return if condition evaluates True. 43 :param false_value: Value to return if condition evaluates False. 44 """ 45 return true_value if condition else false_value 46 47 48def tryint(value, default=0): 49 '''Attempt to cast the given value to an integer, return the default if an exception occurs. 50 51 :param value: The value to cast. 52 :param int default: The default on error. 53 ''' 54 try: 55 return int(value) 56 except (TypeError, ValueError): 57 return default 58