def __getitem__(self, item): if item == self.DATA_KEY: return self.data elif gx.is_mapping(self._data): if gx.is_str(item): return self._data[item] else: return recursive_getitem(self._data, item) raise KeyError
def __init__(self, pattern): if is_str(pattern): self._parser, self._type = try____( pattern, func=re.compile, afunc=parse.compile, post_error_raise_check=lambda x: '(?P<' in x, extra_msg= f"tried to parse the provided format object `{pattern}` for `{pattern}` as a regular expression but failed" ) elif type(pattern) is NamedFieldExtractor: self._parser = pattern._parser self._type = pattern._type else: self._parser = pattern self._type = type(pattern) is parse.Parser
def __getitem__(self, item): if self.indices is None: raise RuntimeError( 'index the data first; otherwise the indices are not available' ) if item == self.INDEX_KEY: return self.indices elif item == self.DATA_KEY: return self.data elif gx.is_mapping(self.indices): if gx.is_str(item): return self.indices[item] else: return recursive_getitem(self.indices, item) raise KeyError
def ensure_dir_existence(*dir_path_or_paths, clear_dir=False, verbose=__debug__): """ Creates a directory if the path does not exist. Optionally, set `clear_dir` to `True` to clear an existing directory. >>> import utix.pathex as pathx >>> import os >>> path1, path2 = 'test/_dir1', 'test/_dir2' >>> pathx.print_basic_path_info(path1) >>> pathx.print_basic_path_info(path2) Pass in a single path. ---------------------- >>> pathx.ensure_dir_existence(path1) >>> os.remove(path1) Pass in multiple paths. ----------------------- >>> pathx.ensure_dir_existence(path1, path2) >>> os.remove(path1) >>> os.remove(path2) Pass in multiple paths as a tuple. ---------------------------------- >>> # this is useful when this method is composed with another function that returns multiple paths. >>> def foo(): >>> return path1, path2 >>> pathx.ensure_dir_existence(foo()) :param dir_path_or_paths: one or more paths to check. :param clear_dir: clear the directory if they exist. :return: the input directory paths; this function has guaranteed their existence. """ if len(dir_path_or_paths) == 1 and not isinstance(dir_path_or_paths[0], str): dir_path_or_paths = dir_path_or_paths[0] for dir_path in dir_path_or_paths: if not path.exists(dir_path): if verbose: hprint(msg_create_dir(dir_path)) os.makedirs(dir_path) elif not path.isdir(dir_path): raise ValueError( msg_arg_not_a_dir(path_str=dir_path, arg_name='dir_path_or_paths')) elif clear_dir is True: if verbose: hprint(msg_clear_dir(dir_path)) shutil.rmtree(dir_path) os.makedirs(dir_path) elif is_str(clear_dir) and bool(clear_dir): for file in iter_files_by_pattern(dir_or_dirs=dir_path, pattern=clear_dir, recursive=False): os.remove(file) if verbose: print_basic_path_info(dir_path) return dir_path_or_paths[0] if len( dir_path_or_paths) == 1 else dir_path_or_paths