Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@awan1
Last active October 30, 2015 00:07
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 awan1/bc198d8ca81a7805a0cc to your computer and use it in GitHub Desktop.
Save awan1/bc198d8ca81a7805a0cc to your computer and use it in GitHub Desktop.
Flexibly check that the result of os.path.join is of a given type.
"""
Wrapper call to os.path.join and os.path.expanduser that checks whether the
returned path is of a given type.
Author: awan1
Date: 20151029
"""
import os
def path_join_check(a, *p, **kwargs):
"""
Wrapper to os.path.join and os.path.expanduser, raising an error if the
resultant path is not of a specified type.
The expected type of the path is specified in kwargs via the named argument
'typ'.
Parameters:
a, *p: arguments to os.path.join
kwargs:
typ: the expected type of path. Valid inputs specified by valid_typs. If typ
is 'any', checks that the path matches one of the valid types. typ must
be passed in.
(Use kwargs to preserve initial syntax of os.path.join)
Returns:
Result of os.path.expanduser(os.path.join(...))
Raises error if resultant path is not of type specified by typ.
"""
# The typ value for which to check all valid typs
any_typ_name = 'any'
# Structure of typs_and_checks:
# keys: valid typs
# values: tuples of (the checking operation to perform, the return condition)
typs_and_checks = {'dir': (os.path.isdir, True),
'file': (os.path.isfile, True)}
valid_typs = typs_and_checks.keys()
try:
typ = kwargs['typ']
except KeyError:
raise Exception("path_join_check expects a keyword argument typ")
if typ == any_typ_name:
any_typ = True
else:
any_typ = False
if typ not in valid_typs:
raise Exception("typ {} not supported.".format(typ))
path = os.path.expanduser(os.path.join(a, *p))
for valid_typ, (check_op, ret_cond) in typs_and_checks.iteritems():
if any_typ or typ == valid_typ:
if check_op(path) == ret_cond: return path
# If we reach here, we didn't get a good path.
raise Exception("{} is not of type {}".format(path, typ))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment