code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def find_cell_with_tag(nb, tag): """ Find a cell with a given tag, returns a cell, index tuple. Otherwise (None, None) """ out = find_cell_with_tags(nb, [tag]) if out: located = out[tag] return located["cell"], located["index"] else: return None, None
Find a cell with a given tag, returns a cell, index tuple. Otherwise (None, None)
find_cell_with_tag
python
ploomber/ploomber
src/ploomber/sources/nb_utils.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/nb_utils.py
Apache-2.0
def _jupytext_fmt(primitive, extension): """ Determine the jupytext fmt string to use based on the content and extension """ if extension.startswith("."): extension = extension[1:] if extension != "ipynb": fmt, _ = jupytext.guess_format(primitive, f".{extension}") fmt_final ...
Determine the jupytext fmt string to use based on the content and extension
_jupytext_fmt
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def _get_last_cell(nb): """ Get last cell, ignores cells with empty source (unless the notebook only has one cell and it's empty) """ # iterate in reverse order for idx in range(-1, -len(nb.cells) - 1, -1): cell = nb.cells[idx] # only return it if it has some code if cel...
Get last cell, ignores cells with empty source (unless the notebook only has one cell and it's empty)
_get_last_cell
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def requires_path(func): """ Checks if NotebookSource instance was initialized from a file, raises an error if not """ @wraps(func) def wrapper(self, *args, **kwargs): if self._path is None: raise ValueError( f"Cannot use {func.__name__!r} if notebook was " ...
Checks if NotebookSource instance was initialized from a file, raises an error if not
requires_path
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def _read_nb_str_unrendered(self, force=False): """ Returns the notebook representation (JSON string), this is the raw source code passed, does not contain injected parameters. Adds kernelspec info if not present based on the kernelspec_name, this metadata is required for paperm...
Returns the notebook representation (JSON string), this is the raw source code passed, does not contain injected parameters. Adds kernelspec info if not present based on the kernelspec_name, this metadata is required for papermill to know which kernel to use. An exception is r...
_read_nb_str_unrendered
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def _validate_parameters_cell(self, extract_upstream=False, extract_product=False): """Check parameters call and add it when it's missing Parameters ---------- extract_upstream : bool, default: False Flags used to determine the content of the parameters cell, onl...
Check parameters call and add it when it's missing Parameters ---------- extract_upstream : bool, default: False Flags used to determine the content of the parameters cell, only used if the notebook is missing the parameters cell extract_product : bool, default: ...
_validate_parameters_cell
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def _post_render_validation(self): """ Validate params passed against parameters in the notebook """ # NOTE: maybe static_analysis = off should not turn off everything # but only warn # strict mode: raise and check signature # regular mode: _check_notebook called...
Validate params passed against parameters in the notebook
_post_render_validation
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def nb_str_rendered(self): """ Returns the notebook (as a string) with parameters injected, hot reloadig if necessary """ if self._nb_str_rendered is None: raise RuntimeError( "Attempted to get location for an unrendered " "notebook, re...
Returns the notebook (as a string) with parameters injected, hot reloadig if necessary
nb_str_rendered
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def nb_obj_rendered(self): """ Returns the notebook (as an objet) with parameters injected, hot reloadig if necessary """ if self._nb_obj_rendered is None: # using self.nb_str_rendered triggers hot reload if needed self._nb_obj_rendered = self._nb_str_to_o...
Returns the notebook (as an objet) with parameters injected, hot reloadig if necessary
nb_obj_rendered
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def language(self): """ Notebook Language (Python, R, etc), this is a best-effort property, can be None if we could not determine the language """ if self._language is None: self._read_nb_str_unrendered() try: # make sure you return "r" in...
Notebook Language (Python, R, etc), this is a best-effort property, can be None if we could not determine the language
language
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def save_injected_cell(self, **kwargs): """ Inject cell, overwrite the source file (and any paired files) """ fmt_ = _jupytext_fmt(self._primitive, self._ext_in) # add metadata to flag that the cell was injected manually recursive_update( self.nb_obj_rendered...
Inject cell, overwrite the source file (and any paired files)
save_injected_cell
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def remove_injected_cell(self): """ Delete injected cell, overwrite the source file (and any paired files) """ nb_clean = _cleanup_rendered_nb(self._nb_obj_unrendered) # remove metadata recursive_update( nb_clean, dict(metadata=dict(ploomber=dict(injected_man...
Delete injected cell, overwrite the source file (and any paired files)
remove_injected_cell
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def format(self, fmt, entry_point): """Change source format Returns ------- str The path if the extension changed, None otherwise """ nb_clean = _cleanup_rendered_nb(self._nb_obj_unrendered) ext_file = self._path.suffix ext_format = long_form...
Change source format Returns ------- str The path if the extension changed, None otherwise
format
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def _to_nb_obj( source, language, ext=None, kernelspec_name=None, check_if_kernel_installed=True, path=None, ): """ Convert to jupyter notebook via jupytext, if the notebook does not contain kernel information and the user did not pass a kernelspec_name explicitly, we will try to...
Convert to jupyter notebook via jupytext, if the notebook does not contain kernel information and the user did not pass a kernelspec_name explicitly, we will try to infer the language and select a kernel appropriately. If a valid kernel is found, it is added to the notebook. If none of this works,...
_to_nb_obj
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def check_nb_kernelspec_info( nb, kernelspec_name, ext, language, check_if_installed=True ): """Make sure the passed notebook has kernel info Parameters ---------- check_if_installed : bool Also check if the kernelspec is installed, nb.metadata.kernelspec to be replaced by whatever ...
Make sure the passed notebook has kernel info Parameters ---------- check_if_installed : bool Also check if the kernelspec is installed, nb.metadata.kernelspec to be replaced by whatever information jupyter returns when requesting the kernelspec
check_nb_kernelspec_info
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def determine_kernel_name(nb, kernelspec_name, ext, language): """ Determines the kernel name by using the following data (returns whatever gives kernel info first): 1) explicit kernel from the user 2) notebook's metadata 3) file extension 4) language 5) best guess """ # explicit kernelspec name...
Determines the kernel name by using the following data (returns whatever gives kernel info first): 1) explicit kernel from the user 2) notebook's metadata 3) file extension 4) language 5) best guess
determine_kernel_name
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def inject_cell(model, params): """Inject params (by adding a new cell) to a model Notes ----- A model is different than a notebook: https://jupyter-server.readthedocs.io/en/stable/developers/contents.html """ nb = nbformat.from_dict(model["content"]) # we must ensure nb has kernelspec...
Inject params (by adding a new cell) to a model Notes ----- A model is different than a notebook: https://jupyter-server.readthedocs.io/en/stable/developers/contents.html
inject_cell
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def _cleanup_rendered_nb(nb, print_=True): """ Cleans up a rendered notebook object. Removes cells with tags: injected-parameters, debugging-settings, and metadata injected by papermill """ out = find_cell_with_tags(nb, ["injected-parameters", "debugging-settings"]) if print_: for k...
Cleans up a rendered notebook object. Removes cells with tags: injected-parameters, debugging-settings, and metadata injected by papermill
_cleanup_rendered_nb
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def is_python(nb): """ Determine if the notebook is Python code for a given notebook object, look for metadata.kernelspec.language first, if not defined, try to guess if it's Python, it's conservative and it returns False if the code is valid Python but contains (<-), in which case it's much more li...
Determine if the notebook is Python code for a given notebook object, look for metadata.kernelspec.language first, if not defined, try to guess if it's Python, it's conservative and it returns False if the code is valid Python but contains (<-), in which case it's much more likely to be R
is_python
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def determine_language(extension): """ A function to determine programming language given file extension, returns programming language name (all lowercase) if could be determined, None if the test is inconclusive """ if extension.startswith("."): extension = extension[1:] mapping = ...
A function to determine programming language given file extension, returns programming language name (all lowercase) if could be determined, None if the test is inconclusive
determine_language
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def recursive_update(target, update): """Recursively update a dictionary. Taken from jupytext.header""" for key in update: value = update[key] if value is None: # remove if it exists target.pop(key, None) elif isinstance(value, dict): target[key] = rec...
Recursively update a dictionary. Taken from jupytext.header
recursive_update
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def parse_jupytext_format(fmt, name): """ Parse a jupytext format string (such as notebooks//ipynb) and return the path to the file and the extension """ fmt_parsed = long_form_one_format(fmt) path = Path(fmt_parsed["prefix"], f'{name}{fmt_parsed["extension"]}') del fmt_parsed["prefix"] ...
Parse a jupytext format string (such as notebooks//ipynb) and return the path to the file and the extension
parse_jupytext_format
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def add_parameters_cell(path, extract_upstream=False, extract_product=False): """ Add parameters cell to a script/notebook in the given path, overwrites the original file """ source = "" if extract_upstream: source += """\ # declare a list tasks whose products you want to use as inputs ...
Add parameters cell to a script/notebook in the given path, overwrites the original file
add_parameters_cell
python
ploomber/ploomber
src/ploomber/sources/notebooksource.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/notebooksource.py
Apache-2.0
def _post_render_validation(self, rendered_value, params): """Analyze code and warn if issues are found""" if "product" in params: inferred_relations = set( static_analysis.sql.created_relations( rendered_value, split_source=self._split_source ...
Analyze code and warn if issues are found
_post_render_validation
python
ploomber/ploomber
src/ploomber/sources/sources.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/sources.py
Apache-2.0
def _validate_top_keys(self, spec, path): """Validate keys at the top of the spec""" if "tasks" not in spec and "location" not in spec: raise DAGSpecInitializationError( 'Failed to initialize spec. Missing "tasks" key' ) if "location" in spec: ...
Validate keys at the top of the spec
_validate_top_keys
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def to_dag(self): """Converts the DAG spec to a DAG object""" # when initializing DAGs from pipeline.yaml files, we have to ensure # that the folder where pipeline.yaml is located is in sys.path for # imports to work (for dag clients), this happens most of the time but # for some...
Converts the DAG spec to a DAG object
to_dag
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def _to_dag(self): """ Internal method to manage the different cases to convert to a DAG object """ if "location" in self: return dotted_path.call_dotted_path(self["location"]) dag = DAG(name=self._name) if "config" in self: dag._params =...
Internal method to manage the different cases to convert to a DAG object
_to_dag
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def find( cls, env=None, reload=False, lazy_import=False, starting_dir=None, name=None ): """ Automatically find pipeline.yaml and return a DAGSpec object, which can be converted to a DAG using .to_dag() Parameters ---------- env The environment t...
Automatically find pipeline.yaml and return a DAGSpec object, which can be converted to a DAG using .to_dag() Parameters ---------- env The environment to pass to the spec name : str, default=None Filename to search for. If None, it looks for a ...
find
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def from_directory(cls, path_to_dir): """ Construct a DAGSpec from a directory. Product and upstream are extracted from sources Parameters ---------- path_to_dir : str The directory to use. Looks for scripts (``.py``, ``.R`` or ``.ipynb``) in the...
Construct a DAGSpec from a directory. Product and upstream are extracted from sources Parameters ---------- path_to_dir : str The directory to use. Looks for scripts (``.py``, ``.R`` or ``.ipynb``) in the directory and interprets them as tas...
from_directory
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def from_files(cls, files): """ Construct DAGSpec from list of files or glob-like pattern. Product and upstream are extracted from sources Parameters ---------- files : list or str List of files to use or glob-like string pattern. If glob-like pat...
Construct DAGSpec from list of files or glob-like pattern. Product and upstream are extracted from sources Parameters ---------- files : list or str List of files to use or glob-like string pattern. If glob-like pattern, ignores directories that match th...
from_files
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def initialize_inplace(cls, data): """Validate and instantiate the "meta" section""" if "meta" not in data: data["meta"] = {} data["meta"] = Meta.default_meta(data["meta"])
Validate and instantiate the "meta" section
initialize_inplace
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def default_meta(cls, meta=None): """Fill missing values in a meta dictionary""" if meta is None: meta = {} validate.keys(cls.VALID, meta, name="dag spec") if "extract_upstream" not in meta: meta["extract_upstream"] = True if "extract_product" not in me...
Fill missing values in a meta dictionary
default_meta
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def process_tasks(dag, dag_spec, root_path=None): """ Initialize Task objects from TaskSpec, extract product and dependencies if needed and set the dag dependencies structure """ root_path = root_path or "." # options extract_up = dag_spec["meta"]["extract_upstream"] extract_prod = dag_...
Initialize Task objects from TaskSpec, extract product and dependencies if needed and set the dag dependencies structure
process_tasks
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def _expand_upstream(upstream, task_names): """ Processes a list of upstream values extracted from source (or declared in the spec's "upstream" key). Expands wildcards like "some-task-*" to all the values that match. Returns a dictionary where keys are the upstream dependencies and the corresponding...
Processes a list of upstream values extracted from source (or declared in the spec's "upstream" key). Expands wildcards like "some-task-*" to all the values that match. Returns a dictionary where keys are the upstream dependencies and the corresponding value is the wildcard. If no wildcard, the val...
_expand_upstream
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def _build_example_spec(source): """ Build an example spec from just the source. """ example_spec = {} example_spec["source"] = source if suffix2taskclass[Path(source).suffix] is NotebookRunner: example_product = { "nb": "products/report.ipynb", "data": "products/...
Build an example spec from just the source.
_build_example_spec
python
ploomber/ploomber
src/ploomber/spec/dagspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/dagspec.py
Apache-2.0
def task_class_from_source_str(source_str, lazy_import, reload, product): """ The source field in a DAG spec is a string. The actual value needed to instantiate the task depends on the task class, but to make task class optional, we try to guess the appropriate task here. If the source_str needs any...
The source field in a DAG spec is a string. The actual value needed to instantiate the task depends on the task class, but to make task class optional, we try to guess the appropriate task here. If the source_str needs any pre-processing to pass it to the task constructor, it also happens here. If ...
task_class_from_source_str
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def task_class_from_spec(task_spec, lazy_import, reload): """ Returns the class for the TaskSpec, if the spec already has the class name (str), it just returns the actual class object with such name, otherwise it tries to guess based on the source string """ class_name = task_spec.get("class", N...
Returns the class for the TaskSpec, if the spec already has the class name (str), it just returns the actual class object with such name, otherwise it tries to guess based on the source string
task_class_from_spec
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def _init_source_for_task_class( source_str, task_class, project_root, lazy_import, make_absolute ): """ Initialize source. Loads dotted path to callable if a PythonCallable task, otherwise it returns a path """ if task_class is tasks.PythonCallable: if lazy_import: return so...
Initialize source. Loads dotted path to callable if a PythonCallable task, otherwise it returns a path
_init_source_for_task_class
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def to_task(self, dag): """ Convert the spec to a Task or TaskGroup and add it to the dag. Returns a (task, upstream) tuple with the Task instance and list of upstream dependencies (as described in the 'upstream' key, if any, empty if no 'upstream' key). If the spec has a 'grid' ...
Convert the spec to a Task or TaskGroup and add it to the dag. Returns a (task, upstream) tuple with the Task instance and list of upstream dependencies (as described in the 'upstream' key, if any, empty if no 'upstream' key). If the spec has a 'grid' key, a TaskGroup instance i...
to_task
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def _init_task(data, meta, project_root, lazy_import, dag): """Initialize a single task from a dictionary spec""" task_dict = copy(data) class_ = task_dict.pop("class") product = _init_product( task_dict, meta, class_, project_root, lazy_import=lazy_import ) _init_client(task_dict, laz...
Initialize a single task from a dictionary spec
_init_task
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def try_product_init(class_, product_raw, relative_to, kwargs): """Initializes Product (or MetaProduct) Parameters ---------- class_ : class Product class product_raw : str, list or dict The raw value as indicated by the user in the pipeline.yaml file. str if a single file,...
Initializes Product (or MetaProduct) Parameters ---------- class_ : class Product class product_raw : str, list or dict The raw value as indicated by the user in the pipeline.yaml file. str if a single file, list if a SQL relation or dict if a MetaProduct relative_to : str...
try_product_init
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def _try_product_init(class_, path_to_source, kwargs): """ Try to initialize product, raises a chained exception if not possible. To provide more context. """ try: return class_(path_to_source, **kwargs) except Exception as e: kwargs_msg = f" and keyword arguments: {kwargs!r}" if...
Try to initialize product, raises a chained exception if not possible. To provide more context.
_try_product_init
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def resolve_if_file(product_raw, relative_to, class_): """Resolve Product argument if it's a File to make it an absolute path""" try: return _resolve_if_file(product_raw, relative_to, class_) except Exception as e: e.args = ("Error initializing File with argument " f"{product_raw!r} ({e})",)...
Resolve Product argument if it's a File to make it an absolute path
resolve_if_file
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def _resolve_if_file(product_raw, relative_to, class_): """Resolve File argument to make it an absolute path""" # not a file, nothing to do... if class_ != products.File: return product_raw # resolve... elif relative_to: # To keep things consistent, product relative paths are so to t...
Resolve File argument to make it an absolute path
_resolve_if_file
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def _preprocess_grid_spec(grid_spec): """ Preprocess a grid (list or dictionary) to expand values if it contains dotted paths """ if isinstance(grid_spec, Mapping): return _process_dotted_paths(grid_spec) else: out = [] for element in grid_spec: out.append(_p...
Preprocess a grid (list or dictionary) to expand values if it contains dotted paths
_preprocess_grid_spec
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def _process_dotted_paths(grid_spec): """ Preprocess a grid (dictionary) to expand values if it contains dotted paths """ out = dict() for key, value in grid_spec.items(): try: dp = dotted_path.DottedPath(value, allow_return_none=False, strict=True) # TypeError: not ...
Preprocess a grid (dictionary) to expand values if it contains dotted paths
_process_dotted_paths
python
ploomber/ploomber
src/ploomber/spec/taskspec.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/spec/taskspec.py
Apache-2.0
def find_variable_access(self, variable): """ Find occurrences of {{variable.something}} and {{variable['something']}} """ attr = self.ast.find_all(Getattr) item = self.ast.find_all(Getitem) return ( set( [ obj.arg....
Find occurrences of {{variable.something}} and {{variable['something']}}
find_variable_access
python
ploomber/ploomber
src/ploomber/static_analysis/jinja.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/jinja.py
Apache-2.0
def find_variable_assignment(self, variable): """ Find a variable assignment: {% set variable = something %}, returns the node that assigns the variable """ variables = {n.target.name: n.node for n in self.ast.find_all(Assign)} return None if variable not in variables els...
Find a variable assignment: {% set variable = something %}, returns the node that assigns the variable
find_variable_assignment
python
ploomber/ploomber
src/ploomber/static_analysis/jinja.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/jinja.py
Apache-2.0
def unexpectedError(self, *args, **kwargs): """pyflakes calls this when ast.parse raises an unexpected error""" self._unexpected = True return super().unexpectedError(*args, **kwargs)
pyflakes calls this when ast.parse raises an unexpected error
unexpectedError
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def syntaxError(self, *args, **kwargs): """pyflakes calls this when ast.parse raises a SyntaxError""" self._syntax = True return super().syntaxError(*args, **kwargs)
pyflakes calls this when ast.parse raises a SyntaxError
syntaxError
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def check_notebook(nb, params, filename, raise_=True, check_signature=True): """ Perform static analysis on a Jupyter notebook code cell sources Parameters ---------- nb : NotebookNode Notebook object. Must have a cell with the tag "parameters" params : dict Parameter that will...
Perform static analysis on a Jupyter notebook code cell sources Parameters ---------- nb : NotebookNode Notebook object. Must have a cell with the tag "parameters" params : dict Parameter that will be added to the notebook source filename : str Filename to identify py...
check_notebook
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def check_source(nb, raise_=True): """ Run pyflakes on a notebook, wil catch errors such as missing passed parameters that do not have default values """ # concatenate all cell's source code in a single string source_code = "\n".join( [ _comment_if_ipython_magic(c["source"]) ...
Run pyflakes on a notebook, wil catch errors such as missing passed parameters that do not have default values
check_source
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def _comment_if_ipython_magic(source): """Comments lines into comments if they're IPython magics (cell level)""" # TODO: support for nested cell magics. e.g., # %%timeit # %%timeit # something() lines_out = [] comment_rest = False # TODO: inline magics should add a comment at the end of...
Comments lines into comments if they're IPython magics (cell level)
_comment_if_ipython_magic
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def _is_ipython_cell_magic(source): """Determines if the source is an IPython cell magic. e.g., %cd some-directory """ m = re.match(_IS_IPYTHON_CELL_MAGIC, source.lstrip()) if not m: return False return m.group()
Determines if the source is an IPython cell magic. e.g., %cd some-directory
_is_ipython_cell_magic
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def check_params(passed, params_source, filename, warn=False): """ Check that parameters passed to the notebook match the ones defined in the parameters variable Parameters ---------- passed : iterable Paramters passed to the notebook (params argument) params_source : str P...
Check that parameters passed to the notebook match the ones defined in the parameters variable Parameters ---------- passed : iterable Paramters passed to the notebook (params argument) params_source : str Parameters cell source code filename : str The task's file...
check_params
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def _get_defined_variables(params_source): """ Return the variables defined in a given source. If a name is defined more than once, it uses the last definition. Ignores anything other than variable assignments (e.g., function definitions, exceptions) """ used_names = parso.parse(params_source).g...
Return the variables defined in a given source. If a name is defined more than once, it uses the last definition. Ignores anything other than variable assignments (e.g., function definitions, exceptions)
_get_defined_variables
python
ploomber/ploomber
src/ploomber/static_analysis/pyflakes.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/pyflakes.py
Apache-2.0
def extract_product(self): """ Extract "product" from a Python code string """ product_found, product = extract_variable(self.parameters_cell, "product") if not product_found or product is None: raise ValueError( "Couldn't extract 'product' " f"from c...
Extract "product" from a Python code string
extract_product
python
ploomber/ploomber
src/ploomber/static_analysis/python.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/python.py
Apache-2.0
def extract_upstream(self): """ Extract keys requested to an upstream variable (e.g. upstream['key']) """ module = ast.parse(self.code) return { get_value(node) for node in ast.walk(module) if isinstance(node, ast.Subscript) and get...
Extract keys requested to an upstream variable (e.g. upstream['key'])
extract_upstream
python
ploomber/ploomber
src/ploomber/static_analysis/python.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/python.py
Apache-2.0
def extract_variable(code_str, name): """ Get the value assigned to a variable with name "name" by passing a code string """ variable_found = False value = None for stmt in _iterate_assignments(code_str): if hasattr(stmt, "get_defined_names"): defined = stmt.get_defined_...
Get the value assigned to a variable with name "name" by passing a code string
extract_variable
python
ploomber/ploomber
src/ploomber/static_analysis/python.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/python.py
Apache-2.0
def extract_upstream_assign(cell_code): """ Infer dependencies from a single Python cell. Looks for a cell that defines an upstream variable which must be either a dictionary or None """ upstream_found, upstream = extract_variable(cell_code, "upstream") if not upstream_found: raise Valu...
Infer dependencies from a single Python cell. Looks for a cell that defines an upstream variable which must be either a dictionary or None
extract_upstream_assign
python
ploomber/ploomber
src/ploomber/static_analysis/python.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/python.py
Apache-2.0
def naive_parsing(code, var_name): """ Our current R parser can only deal with a single statement (one line) at a time. So we parse on a per-line basis and look for the variable we want, this will be replaced for a more efficient implementation once we improve the parser """ for code in code...
Our current R parser can only deal with a single statement (one line) at a time. So we parse on a per-line basis and look for the variable we want, this will be replaced for a more efficient implementation once we improve the parser
naive_parsing
python
ploomber/ploomber
src/ploomber/static_analysis/r.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/r.py
Apache-2.0
def extract_product(self, raise_if_none=True): """ Extract an object from a SQL template that defines as product variable: {% set product = SOME_CLASS(...) %} Where SOME_CLASS is a class defined in ploomber.products. If no product variable is defined, returns None """ ...
Extract an object from a SQL template that defines as product variable: {% set product = SOME_CLASS(...) %} Where SOME_CLASS is a class defined in ploomber.products. If no product variable is defined, returns None
extract_product
python
ploomber/ploomber
src/ploomber/static_analysis/sql.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/sql.py
Apache-2.0
def _normalize(identifier): """ Normalize a SQL identifier. Given that different SQL implementations have different rules, we will implement logic based on PostgreSQL. Double quotes make an identifier case sensitive, unquoted are forced to lower case. MySQL on the other hand, depends on the file sys...
Normalize a SQL identifier. Given that different SQL implementations have different rules, we will implement logic based on PostgreSQL. Double quotes make an identifier case sensitive, unquoted are forced to lower case. MySQL on the other hand, depends on the file system, furthermore the quoting id...
_normalize
python
ploomber/ploomber
src/ploomber/static_analysis/sql.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/sql.py
Apache-2.0
def parse(self): """The current implementation can only parse one expression at a time""" if not isinstance(self.current_token, Name): raise SyntaxError("First token must be a valid name") if not isinstance(self.next_token, Assignment): raise SyntaxError("Second token mu...
The current implementation can only parse one expression at a time
parse
python
ploomber/ploomber
src/ploomber/static_analysis/parser/parser.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/static_analysis/parser/parser.py
Apache-2.0
def upstream(self): """ A mapping for upstream dependencies {task name} -> [task object] """ # this is just syntactic sugar, upstream relations are tracked by the # DAG object # this always return a copy to prevent global state if contents # are modified (e.g. by...
A mapping for upstream dependencies {task name} -> [task object]
upstream
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def _upstream_product_grouped(self): """ Similar to .upstream but this one nests groups. Output will be the same as .upstream if no upstream dependencies are grouped. This is only used internally in .render to correctly pass upstream to task.params. Unlike .upstream, thi...
Similar to .upstream but this one nests groups. Output will be the same as .upstream if no upstream dependencies are grouped. This is only used internally in .render to correctly pass upstream to task.params. Unlike .upstream, this method returns products instead of task names ...
_upstream_product_grouped
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def _lineage(self): """ Set with task names of all the dependencies for this task (including dependencies of dependencies) """ # if no upstream deps, there is no lineage if not len(self.upstream): return None else: # retrieve lineage: upstr...
Set with task names of all the dependencies for this task (including dependencies of dependencies)
_lineage
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def _post_run_actions(self): """ Call on_finish hook, save metadata, verify products exist and upload product """ # run on finish first, if this fails, we don't want to save metadata try: self._run_on_finish() except Exception: # NOTE: we a...
Call on_finish hook, save metadata, verify products exist and upload product
_post_run_actions
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def build(self, force=False, catch_exceptions=True): """Build a single task Although Tasks are primarily designed to execute via DAG.build(), it is possible to do so in isolation. However, this only works if the task does not have any unrendered upstream dependencies, if that's the ...
Build a single task Although Tasks are primarily designed to execute via DAG.build(), it is possible to do so in isolation. However, this only works if the task does not have any unrendered upstream dependencies, if that's the case, you should call DAG.render() before calling Task.build...
build
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def _build(self, catch_exceptions): """ Private API for building DAGs. This is what executors should call. Unlike the public method, this one does not call render, as it should happen via a dag.render() call. It takes care of running the task and updating status accordingly ...
Private API for building DAGs. This is what executors should call. Unlike the public method, this one does not call render, as it should happen via a dag.render() call. It takes care of running the task and updating status accordingly Parameters ---------- catch...
_build
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def _run(self): """ Run or download task if certain status conditions are met, otherwise raise a TaskBuildError exception """ # cannot keep running, we depend on the render step to get all the # parameters resolved (params, upstream, product) if self.exec_status =...
Run or download task if certain status conditions are met, otherwise raise a TaskBuildError exception
_run
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def render(self, force=False, outdated_by_code=True, remote=False): """ Renders code and product, all upstream tasks must have been rendered first, for that reason, this method will usually not be called directly but via DAG.render(), which renders in the right order. Render ful...
Renders code and product, all upstream tasks must have been rendered first, for that reason, this method will usually not be called directly but via DAG.render(), which renders in the right order. Render fully determines whether a task should run or not. Parameters ---...
render
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def status(self, return_code_diff=False, sections=None): """Prints the current task status Parameters ---------- sections : list, optional Sections to include. Defaults to "name", "last_run", "oudated", "product", "doc", "location" """ sections = ...
Prints the current task status Parameters ---------- sections : list, optional Sections to include. Defaults to "name", "last_run", "oudated", "product", "doc", "location"
status
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def debug(self): """Debug task, only implemented in certain tasks""" raise NotImplementedError( '"debug" is not implemented in "{}" tasks'.format(type(self).__name__) )
Debug task, only implemented in certain tasks
debug
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def load(self): """Load task as pandas.DataFrame. Only implemented in certain tasks""" raise NotImplementedError( '"load" is not implemented in "{}" tasks'.format(type(self).__name__) )
Load task as pandas.DataFrame. Only implemented in certain tasks
load
python
ploomber/ploomber
src/ploomber/tasks/abc.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/abc.py
Apache-2.0
def _check_exporter(exporter, path_to_output): """ Validate if the user can use the selected exporter """ if WebPDFExporter is not None and exporter is WebPDFExporter: pyppeteer_installed = find_spec("pyppeteer") is not None if not pyppeteer_installed: raise TaskInitializati...
Validate if the user can use the selected exporter
_check_exporter
python
ploomber/ploomber
src/ploomber/tasks/notebook.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/notebook.py
Apache-2.0
def _get_exporter(exporter_name, path_to_output): """ Get function to convert notebook to another format using nbconvert, first. In some cases, the exporter name matches the file extension (e.g html) but other times it doesn't (e.g. slides), use `nbconvert.get_export_names()` to ...
Get function to convert notebook to another format using nbconvert, first. In some cases, the exporter name matches the file extension (e.g html) but other times it doesn't (e.g. slides), use `nbconvert.get_export_names()` to get available exporter_names Returns None if passed ...
_get_exporter
python
ploomber/ploomber
src/ploomber/tasks/notebook.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/notebook.py
Apache-2.0
def debug(self, kind="ipdb"): """ Opens the notebook (with injected parameters) in debug mode in a temporary location Parameters ---------- kind : str, default='ipdb' Debugger to use, 'ipdb' to use line-by-line IPython debugger, 'pdb' to use line-...
Opens the notebook (with injected parameters) in debug mode in a temporary location Parameters ---------- kind : str, default='ipdb' Debugger to use, 'ipdb' to use line-by-line IPython debugger, 'pdb' to use line-by-line Python debugger or 'pm' to to ...
debug
python
ploomber/ploomber
src/ploomber/tasks/notebook.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/notebook.py
Apache-2.0
def _read_rendered_notebook(nb_str): """ Read rendered notebook and inject cell with debugging settings """ # add debug cells nb = nbformat.reads(nb_str, as_version=nbformat.NO_CONVERT) nbformat_v = nbformat.versions[nb.nbformat] source = """ # Debugging settings (this cell will be removed ...
Read rendered notebook and inject cell with debugging settings
_read_rendered_notebook
python
ploomber/ploomber
src/ploomber/tasks/notebook.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/notebook.py
Apache-2.0
def input_data_passer(dag, name, preprocessor=None): """ Returns a special in-memory task that forwards input data as product to downstream tasks. Parameters ---------- dag : ploomber.DAG DAG where the task should be added name : str Task name preprocessor : callable, ...
Returns a special in-memory task that forwards input data as product to downstream tasks. Parameters ---------- dag : ploomber.DAG DAG where the task should be added name : str Task name preprocessor : callable, default=None An arbitrary callable that can be used ...
input_data_passer
python
ploomber/ploomber
src/ploomber/tasks/param_forward.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/param_forward.py
Apache-2.0
def from_grid( cls, task_class, product_class, product_primitive, task_kwargs, dag, grid, name=None, namer=None, resolve_relative_to=None, on_render=None, on_finish=None, on_failure=None, params=None, ): ...
Build a group of tasks of the same class from an grid of parameters using the same source. Parameters ---------- grid : dict or list of dicts If dict, all combinations of individual parameters are generated. If list of dicts, each dict is processed indiv...
from_grid
python
ploomber/ploomber
src/ploomber/tasks/taskgroup.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/taskgroup.py
Apache-2.0
def _unserialize_params(params_original, unserializer): """ User the user-provided function to unserialize params['upstream'] """ params = params_original.to_dict() params["upstream"] = { k: _unserializer(v, unserializer) for k, v in params["upstream"].items() } params = Params._fr...
User the user-provided function to unserialize params['upstream']
_unserialize_params
python
ploomber/ploomber
src/ploomber/tasks/tasks.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/tasks.py
Apache-2.0
def debug(self, kind="ipdb"): """ Run callable in debug mode. Parameters ---------- kind : str ('ipdb' or 'pdb') Which debugger to use 'ipdb' for IPython debugger or 'pdb' for debugger from the standard library Notes ----- Be care...
Run callable in debug mode. Parameters ---------- kind : str ('ipdb' or 'pdb') Which debugger to use 'ipdb' for IPython debugger or 'pdb' for debugger from the standard library Notes ----- Be careful when debugging tasks. If the task has...
debug
python
ploomber/ploomber
src/ploomber/tasks/tasks.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/tasks.py
Apache-2.0
def load(self, key=None, **kwargs): """ Loads the product. It uses the unserializer function if any, otherwise it tries to load it based on the file extension Parameters ---------- key Key to load, if this task generates more than one product **kwarg...
Loads the product. It uses the unserializer function if any, otherwise it tries to load it based on the file extension Parameters ---------- key Key to load, if this task generates more than one product **kwargs Arguments passed to the unseriali...
load
python
ploomber/ploomber
src/ploomber/tasks/tasks.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/tasks.py
Apache-2.0
def task_factory(_func=None, **factory_kwargs): """Syntactic sugar for building PythonCallable tasks""" def decorator(func): @functools.wraps(func) def wrapper(**wrapper_kwargs): kwargs = {**factory_kwargs, **wrapper_kwargs} return PythonCallable(func, **kwargs) ...
Syntactic sugar for building PythonCallable tasks
task_factory
python
ploomber/ploomber
src/ploomber/tasks/tasks.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/tasks.py
Apache-2.0
def download_products_in_parallel(tasks): """Call Task.product.download in parallel""" with ThreadPoolExecutor(max_workers=64) as executor: future2task = {executor.submit(t.product.download): t for t in tasks} for future in as_completed(future2task): exception = future.exception() ...
Call Task.product.download in parallel
download_products_in_parallel
python
ploomber/ploomber
src/ploomber/tasks/util.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/util.py
Apache-2.0
def _from_dict(cls, params, copy=True): """ Private API for initializing Params objects with arbitrary dictionary """ obj = cls(params=None) if copy: obj._dict = copy_module.copy(params) else: obj._dict = params return obj
Private API for initializing Params objects with arbitrary dictionary
_from_dict
python
ploomber/ploomber
src/ploomber/tasks/_params.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/_params.py
Apache-2.0
def to_json_serializable(self, params_only=False): """ Converts params into a dictionary Parameters ---------- params_only : bool, default=False If True, it only returns user params, excluding 'upstream' and 'product' """ out = self.to_dic...
Converts params into a dictionary Parameters ---------- params_only : bool, default=False If True, it only returns user params, excluding 'upstream' and 'product'
to_json_serializable
python
ploomber/ploomber
src/ploomber/tasks/_params.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/tasks/_params.py
Apache-2.0
def nulls_in_columns(cols, product): """Check if any column has NULL values, returns bool""" df = load_product(product) return df.isna().values.sum() > 0
Check if any column has NULL values, returns bool
nulls_in_columns
python
ploomber/ploomber
src/ploomber/testing/pandas.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/pandas.py
Apache-2.0
def duplicates_in_column(col, product): """Check if a column has duplicated values, returns bool""" df = load_product(product) return (df[col].value_counts() > 1).sum() > 0
Check if a column has duplicated values, returns bool
duplicates_in_column
python
ploomber/ploomber
src/ploomber/testing/pandas.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/pandas.py
Apache-2.0
def range_in_column(col, product): """Get range for a column, returns a (min_value, max_value) tuple""" df = load_product(product) return df[col].min(), df[col].max()
Get range for a column, returns a (min_value, max_value) tuple
range_in_column
python
ploomber/ploomber
src/ploomber/testing/pandas.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/pandas.py
Apache-2.0
def _duplicates_query(col, product): """Generate SQL code that counts number of duplicates""" cols = ",".join(_make_iterable(col)) return Template( """ SELECT {{cols}}, COUNT(*) - 1 AS n_duplicates FROM {{product}} GROUP BY {{cols}} HAVING COUNT(*) > 1 """ ).render(cols=cols...
Generate SQL code that counts number of duplicates
_duplicates_query
python
ploomber/ploomber
src/ploomber/testing/sql/duplicated.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/duplicated.py
Apache-2.0
def duplicates_in_column(client, col: Union[str, List[str]], product) -> bool: """Check if a column (or group of columns) has duplicated values Parameters ---------- client Database client cols Column(s) to check product The relation to check Returns ------- ...
Check if a column (or group of columns) has duplicated values Parameters ---------- client Database client cols Column(s) to check product The relation to check Returns ------- bool True if there are duplicates in the column(s). If passed more than ...
duplicates_in_column
python
ploomber/ploomber
src/ploomber/testing/sql/duplicated.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/duplicated.py
Apache-2.0
def assert_no_duplicates_in_column( client, col: Union[str, List[str]], product, stats=False ): """ Assert if there are duplicates in a column (or group of columns). If there are duplicates, it raises an AssertionError with an error message showing some of the duplicated values Parameters -...
Assert if there are duplicates in a column (or group of columns). If there are duplicates, it raises an AssertionError with an error message showing some of the duplicated values Parameters ---------- stats : bool, default=False Whether to show duplicates stats in the error message or ...
assert_no_duplicates_in_column
python
ploomber/ploomber
src/ploomber/testing/sql/duplicated.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/duplicated.py
Apache-2.0
def duplicates_stats(client, col: Union[str, List[str]], product): """Get stats on rows with duplicated values Returns ------- n_rows Number of rows in product n_unique Number of unique values (for selected columns) in product n_duplicates Number of rows with duplicated ...
Get stats on rows with duplicated values Returns ------- n_rows Number of rows in product n_unique Number of unique values (for selected columns) in product n_duplicates Number of rows with duplicated values (this is equal as the number of rows we'd have to drop to r...
duplicates_stats
python
ploomber/ploomber
src/ploomber/testing/sql/duplicated.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/duplicated.py
Apache-2.0
def nulls_in_columns(client, cols: Union[str, List[str]], product): """Check if any column has NULL values, returns bool Parameters ---------- client Database client cols Column(s) to check product The relation to check Returns ------- bool True if t...
Check if any column has NULL values, returns bool Parameters ---------- client Database client cols Column(s) to check product The relation to check Returns ------- bool True if there is at least one NULL in any of the columns
nulls_in_columns
python
ploomber/ploomber
src/ploomber/testing/sql/functions.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/functions.py
Apache-2.0
def distinct_values_in_column(client, col: str, product): """Get distinct values in a column Parameters ---------- client Database client col Column to check product The relation to check Returns ------- set Distinct values in column """ sql ...
Get distinct values in a column Parameters ---------- client Database client col Column to check product The relation to check Returns ------- set Distinct values in column
distinct_values_in_column
python
ploomber/ploomber
src/ploomber/testing/sql/functions.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/functions.py
Apache-2.0
def range_in_column(client, col: str, product): """Get range for a column Parameters ---------- client Database client cols Column to check product The relation to check Returns ------- tuple (minimum, maximum) values """ sql = Template( ...
Get range for a column Parameters ---------- client Database client cols Column to check product The relation to check Returns ------- tuple (minimum, maximum) values
range_in_column
python
ploomber/ploomber
src/ploomber/testing/sql/functions.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/functions.py
Apache-2.0
def exists_row_where(client, criteria: str, product): """ Check whether at least one row exists matching the criteria Parameters ---------- client Database client criteria Criteria to evaluate (passed as argument to a WHERE clause) product The relation to check ...
Check whether at least one row exists matching the criteria Parameters ---------- client Database client criteria Criteria to evaluate (passed as argument to a WHERE clause) product The relation to check Notes ----- Runs a ``SELECT EXISTS (SELECT * FROM {{p...
exists_row_where
python
ploomber/ploomber
src/ploomber/testing/sql/functions.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/testing/sql/functions.py
Apache-2.0
def debug_if_exception(callable_, task_name, kwargs=None): """ Drop a debugger session if running callable_() raises an exception, otherwise it just returns the value returned by callable_() """ # NOTE: importing it here, otherwise we get a # "If you suspect this is an IPython X.Y.Z bug..." mess...
Drop a debugger session if running callable_() raises an exception, otherwise it just returns the value returned by callable_()
debug_if_exception
python
ploomber/ploomber
src/ploomber/util/debug.py
https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/debug.py
Apache-2.0