Skip to content
Snippets Groups Projects

Move list validation to own function

Merged Mayr, Hannes requested to merge improve-list-validation into dev
Files
4
+ 54
1
@@ -2,6 +2,8 @@
# -*- coding: utf-8 -*-
"""Contains the PlotOptions and PlotIDTransfer classes."""
import os
class PlotOptions:
"""
@@ -10,7 +12,10 @@ class PlotOptions:
Methods
-------
__init__
validate_input : Check if input is correct type.
validate_input
Check if input is correct type.
validate_list
Check if all elements of a given list are of certain type.
Attributes
----------
@@ -99,7 +104,55 @@ class PlotIDTransfer:
def __init__(self, figs, figure_ids):
self.figs = figs
self.figure_ids = figure_ids
self.figure_ids = validate_list(self.figure_ids)
def __str__(self):
"""Representation if an object of this class is printed."""
return str(self.__class__) + ": " + str(self.__dict__)
def validate_list(list_var, elt_type=str, is_file=False):
"""
Validate if contents of a list are of specific type.
Parameters
----------
list_var : list or str
List or single string which contents will be validated.
elt_type : datatype, optional
Datatype of which the list elements must be type of. Otherwise
an Error will be raised. The default is str.
is_file : boolean, optional
Flag to indicate if the list contains paths to files. If True the
strings will be checked if they correspond to an existing file.
The default is False.
Raises
------
TypeError
If one of the list elements is not of type elt_type.
FileNotFoundError
If strings are also checked for existing files and one of the files
does not exist.
Returns
-------
list_var as list
"""
if isinstance(list_var, elt_type):
list_var = [list_var]
if isinstance(list_var, list):
for elt in list_var:
if not isinstance(elt, elt_type):
raise TypeError(f'The list of {list_var} contains an '
f'object which is not of type {elt_type}.')
if is_file:
# Check if directory and files exist
if not os.path.exists(elt):
raise FileNotFoundError('The specified directory'
f'/file {elt} does not exist.')
else:
raise TypeError(f'The specified {list_var} are neither a '
f'{elt_type} nor a list of {elt_type}.')
return list_var
Loading