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 render(self, force=False, show_progress=True, remote=False):
"""
Render resolves all placeholders in tasks and determines whether
a task should run or not based on the task.product metadata, this
allows up-to-date tasks to be skipped
Parameters
----------
for... |
Render resolves all placeholders in tasks and determines whether
a task should run or not based on the task.product metadata, this
allows up-to-date tasks to be skipped
Parameters
----------
force : bool, default=False
Ignore product metadata status and prep... | render | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def build(self, force=False, show_progress=True, debug=None, close_clients=True):
"""
Runs the DAG in order so that all upstream dependencies are run for
every task
Parameters
----------
force : bool, default=False
If True, it will run all tasks regardless of... |
Runs the DAG in order so that all upstream dependencies are run for
every task
Parameters
----------
force : bool, default=False
If True, it will run all tasks regardless of status, defaults to
False
show_progress : bool, default=True
... | build | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def close_clients(self):
"""Close all clients (dag-level, task-level and product-level)"""
# keep track of closed clients so we only call .close() once.
# For most clients, calling .close() multiple times does not throw
# any errors. However, when using google.cloud.bigquery.dbapi (and
... | Close all clients (dag-level, task-level and product-level) | close_clients | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def build_partially(
self, target, force=False, show_progress=True, debug=None, skip_upstream=False
):
"""Partially build a dag until certain task
Parameters
----------
target : str
Name of the target task (last one to build). Can pass a wildcard
such... | Partially build a dag until certain task
Parameters
----------
target : str
Name of the target task (last one to build). Can pass a wildcard
such as 'tasks-*'
force : bool, default=False
If True, it will run all tasks regardless of status, defaults t... | build_partially | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def to_markup(self, path=None, fmt="html", sections=None, backend=None):
"""Returns a str (md or html) with the pipeline's description
Parameters
----------
sections : list
Which sections to include, possible values are "plot", "status"
and "source". Defaults to ... | Returns a str (md or html) with the pipeline's description
Parameters
----------
sections : list
Which sections to include, possible values are "plot", "status"
and "source". Defaults to ["plot", "status"]
| to_markup | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def plot(
self, output="embed", include_products=False, backend=None, image_only=False
):
"""Plot the DAG
Parameters
----------
output : str, default='embed'
Where to save the output (e.g., pipeline.png). If 'embed', it
returns an IPython image instea... | Plot the DAG
Parameters
----------
output : str, default='embed'
Where to save the output (e.g., pipeline.png). If 'embed', it
returns an IPython image instead.
include_products : bool, default=False
If False, each node only contains the task name, i... | plot | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def _to_graph(self, fmt, only_current_dag=False, include_products=False):
"""
Converts the DAG to a Networkx DiGraph object. Since upstream
dependencies are not required to come from the same DAG,
this object might include tasks that are not included in the current
object
... |
Converts the DAG to a Networkx DiGraph object. Since upstream
dependencies are not required to come from the same DAG,
this object might include tasks that are not included in the current
object
Parameters
----------
fmt : 'networkx', 'pygraphviz', or 'd3'
... | _to_graph | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def _add_edge(self, task_from, task_to, group_name=None):
"""Add an edge between two tasks
Parameters
----------
group_name : str
Pass a string to group this edge, upon rendering, upstream
products are available via task[group_name][tas_name]
"""
... | Add an edge between two tasks
Parameters
----------
group_name : str
Pass a string to group this edge, upon rendering, upstream
products are available via task[group_name][tas_name]
| _add_edge | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def _get_upstream(self, task_name):
"""Get upstream tasks given a task name (returns Task objects)"""
upstream_names = self._G.predecessors(task_name)
return {name: self._G.nodes[name]["task"] for name in upstream_names} | Get upstream tasks given a task name (returns Task objects) | _get_upstream | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def _clear_metadata(self):
"""
Getting product status (outdated/up-to-date) is slow, especially for
product whose metadata is stored remotely. This is critical when
rendering because we need to do a forward pass to know which tasks to
run and a product's status depends on its ups... |
Getting product status (outdated/up-to-date) is slow, especially for
product whose metadata is stored remotely. This is critical when
rendering because we need to do a forward pass to know which tasks to
run and a product's status depends on its upstream product's status,
and we... | _clear_metadata | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def __iter__(self):
"""
Iterate task names in topological order. Topological order is
desirable in many situations, this order guarantees that for any given
task, its dependencies are executed first, but it's also useful for
other purposes, such as listing tasks, because it shows... |
Iterate task names in topological order. Topological order is
desirable in many situations, this order guarantees that for any given
task, its dependencies are executed first, but it's also useful for
other purposes, such as listing tasks, because it shows a more natural
order t... | __iter__ | python | ploomber/ploomber | src/ploomber/dag/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dag.py | Apache-2.0 |
def create(self, *args, **kwargs):
"""Return a DAG with the given parameters
*args, **kwargs
Parameters to pass to the DAG constructor
"""
dag = DAG(*args, **kwargs)
dag._params = copy(self.params)
return dag | Return a DAG with the given parameters
*args, **kwargs
Parameters to pass to the DAG constructor
| create | python | ploomber/ploomber | src/ploomber/dag/dagconfigurator.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/dagconfigurator.py | Apache-2.0 |
def build(self, input_data, copy=False):
"""Run the DAG
Parameters
----------
input_data : dict
A dictionary mapping root tasks (names) to dict params. Root tasks
are tasks in the DAG that do not have upstream dependencies,
the corresponding dictionar... | Run the DAG
Parameters
----------
input_data : dict
A dictionary mapping root tasks (names) to dict params. Root tasks
are tasks in the DAG that do not have upstream dependencies,
the corresponding dictionary is passed to the respective task
sourc... | build | python | ploomber/ploomber | src/ploomber/dag/inmemorydag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/inmemorydag.py | Apache-2.0 |
def choose_backend(backend, path=None):
"""Determine which backend to use for plotting
Temporarily disable pygraphviz for Python 3.10 on Windows
"""
if (
(not check_pygraphviz_installed() and backend is None)
or (backend == "d3")
or (backend is None and path and Path(path).suffi... | Determine which backend to use for plotting
Temporarily disable pygraphviz for Python 3.10 on Windows
| choose_backend | python | ploomber/ploomber | src/ploomber/dag/plot.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/plot.py | Apache-2.0 |
def json_dag_parser(graph: dict):
"""Format dag dict so d3 can understand it"""
nodes = {}
for task in graph["nodes"]:
nodes[task["id"]] = task
# change name label to products for now
for node in nodes:
nodes[node]["products"] = nodes[node]["label"].replace("\n", "").split(",")
... | Format dag dict so d3 can understand it | json_dag_parser | python | ploomber/ploomber | src/ploomber/dag/plot.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/plot.py | Apache-2.0 |
def with_d3(graph, output, image_only=False):
"""Generates D3 Dag html output and return output file name"""
json_data = json_dag_parser(graph=graph)
if image_only:
Path(output).write_text(json_data)
else:
template = jinja2.Template(
importlib_resources.read_text(resources, "... | Generates D3 Dag html output and return output file name | with_d3 | python | ploomber/ploomber | src/ploomber/dag/plot.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/plot.py | Apache-2.0 |
def check_duplicated_products(dag):
"""
Raises an error if more than one task produces the same product.
Note that this relies on the __hash__ and __eq__ implementations of
each Product to determine whether they're the same or not. This
implies that a relative File and absolute File pointing to the... |
Raises an error if more than one task produces the same product.
Note that this relies on the __hash__ and __eq__ implementations of
each Product to determine whether they're the same or not. This
implies that a relative File and absolute File pointing to the same file
are considered duplicates an... | check_duplicated_products | python | ploomber/ploomber | src/ploomber/dag/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/util.py | Apache-2.0 |
def fetch_remote_metadata_in_parallel(dag):
"""Fetches remote metadta in parallel from a list of Files"""
files = flatten_products(
dag[t].product
for t in dag._iter()
if isinstance(dag[t].product, File) or isinstance(dag[t].product, MetaProduct)
)
if files:
with ThreadP... | Fetches remote metadta in parallel from a list of Files | fetch_remote_metadata_in_parallel | python | ploomber/ploomber | src/ploomber/dag/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/util.py | Apache-2.0 |
def _path_for_plot(path_to_plot, fmt):
"""Context manager to manage DAG.plot
Parameters
----------
path_to_plot : str
Where to store the plot. If 'embed', It returns a temporary empty file
otherwise and deletes it when exiting. Otherwise, it just passes the
value
"""
if ... | Context manager to manage DAG.plot
Parameters
----------
path_to_plot : str
Where to store the plot. If 'embed', It returns a temporary empty file
otherwise and deletes it when exiting. Otherwise, it just passes the
value
| _path_for_plot | python | ploomber/ploomber | src/ploomber/dag/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/dag/util.py | Apache-2.0 |
def load_env(fn):
"""
A function decorated with @load_env will be called with the current
environment in an env keyword argument
"""
_validate_and_modify_signature(fn)
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(Env.load(), *args, **kwargs)
return wrapper |
A function decorated with @load_env will be called with the current
environment in an env keyword argument
| load_env | python | ploomber/ploomber | src/ploomber/env/decorators.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/decorators.py | Apache-2.0 |
def with_env(source):
"""
A function decorated with @with_env that starts and environment during
the execution of a function.
Notes
-----
The first argument of a function decorated with @with_env must be named
"env", the env will be passed automatically when calling the function. The
or... |
A function decorated with @with_env that starts and environment during
the execution of a function.
Notes
-----
The first argument of a function decorated with @with_env must be named
"env", the env will be passed automatically when calling the function. The
original function's signature i... | with_env | python | ploomber/ploomber | src/ploomber/env/decorators.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/decorators.py | Apache-2.0 |
def __init__(self, source="env.yaml"):
"""Start the environment
Parameters
----------
source: dict, pathlib.Path, str, optional
If dict, loads it directly, if pathlib.Path or path, reads the file
(assumes yaml format).
Raises
------
FileN... | Start the environment
Parameters
----------
source: dict, pathlib.Path, str, optional
If dict, loads it directly, if pathlib.Path or path, reads the file
(assumes yaml format).
Raises
------
FileNotFoundError
If source is None and an ... | __init__ | python | ploomber/ploomber | src/ploomber/env/env.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/env.py | Apache-2.0 |
def find(cls, source):
"""
Find env file recursively, currently only used by the @with_env
decorator
"""
if not Path(source).exists():
source_found, _ = default.find_file_recursively(source)
if source_found is None:
raise FileNotFoundError... |
Find env file recursively, currently only used by the @with_env
decorator
| find | python | ploomber/ploomber | src/ploomber/env/envdict.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/envdict.py | Apache-2.0 |
def _replace_value(self, value, keys_all):
"""
Replace a value in the underlying dictionary, by passing a value and
a list of keys
e.g. given {'a': {'b': 1}}, we can replace 1 by doing
_replace_value(2, ['a', 'b'])
"""
keys_to_final_dict = keys_all[:-1]
k... |
Replace a value in the underlying dictionary, by passing a value and
a list of keys
e.g. given {'a': {'b': 1}}, we can replace 1 by doing
_replace_value(2, ['a', 'b'])
| _replace_value | python | ploomber/ploomber | src/ploomber/env/envdict.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/envdict.py | Apache-2.0 |
def _inplace_replace_flatten_key(self, value, key_flatten):
"""
Replace a value in the underlying dictionary, by passing a value and
a list of keys
e.g. given {'a': {'b': 1}}, we can replace 1 by doing
_replace_flatten_keys(2, 'env__a__b'). This function is used
internal... |
Replace a value in the underlying dictionary, by passing a value and
a list of keys
e.g. given {'a': {'b': 1}}, we can replace 1 by doing
_replace_flatten_keys(2, 'env__a__b'). This function is used
internally to overrive env values when calling factories (functions
dec... | _inplace_replace_flatten_key | python | ploomber/ploomber | src/ploomber/env/envdict.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/envdict.py | Apache-2.0 |
def load_from_source(source):
"""
Loads from a dictionary or a YAML and applies preprocesssing to the
dictionary
Returns
-------
dict
Raw dictionary
pathlib.Path
Path to the loaded file, None if source is a dict
str
Name, if loaded from a YAML file with the env.{... |
Loads from a dictionary or a YAML and applies preprocesssing to the
dictionary
Returns
-------
dict
Raw dictionary
pathlib.Path
Path to the loaded file, None if source is a dict
str
Name, if loaded from a YAML file with the env.{name}.yaml format,
None if an... | load_from_source | python | ploomber/ploomber | src/ploomber/env/envdict.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/envdict.py | Apache-2.0 |
def raw_preprocess(raw, path_to_raw):
"""
Preprocess a raw dictionary. If a '_module' key exists, it
will be expanded: first, try to locate a module with that name and resolve
to their location (root __init__.py parent), if no module is found,
interpret as a path to the project's root folder, checks... |
Preprocess a raw dictionary. If a '_module' key exists, it
will be expanded: first, try to locate a module with that name and resolve
to their location (root __init__.py parent), if no module is found,
interpret as a path to the project's root folder, checks that the folder
actually exists. '{{here... | raw_preprocess | python | ploomber/ploomber | src/ploomber/env/envdict.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/envdict.py | Apache-2.0 |
def cast_if_possible(value):
"""
Reference to env in specs must be strings, but we would like the rendered
value to still have the appropriate type
"""
if isinstance(value, str):
value_lower = value.lower()
if value_lower == "false":
return False
elif value_lower... |
Reference to env in specs must be strings, but we would like the rendered
value to still have the appropriate type
| cast_if_possible | python | ploomber/ploomber | src/ploomber/env/expand.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/expand.py | Apache-2.0 |
def expand_raw_value(self, raw_value, parents):
"""
Expand a string with placeholders
Parameters
----------
raw_value : str
The original value to expand
parents : list
The list of parents to get to this value in the dictionary
Notes
... |
Expand a string with placeholders
Parameters
----------
raw_value : str
The original value to expand
parents : list
The list of parents to get to this value in the dictionary
Notes
-----
If for a given raw_value, the first parent... | expand_raw_value | python | ploomber/ploomber | src/ploomber/env/expand.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/expand.py | Apache-2.0 |
def iterate_nested_dict(d):
"""
Iterate over all values (possibly nested) in a dictionary
Yields: dict holding the value, current key, current value, list of keys
to get to this value
"""
for k, v in d.items():
for i in _iterate(d, k, v, preffix=[k]):
yield i |
Iterate over all values (possibly nested) in a dictionary
Yields: dict holding the value, current key, current value, list of keys
to get to this value
| iterate_nested_dict | python | ploomber/ploomber | src/ploomber/env/expand.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/expand.py | Apache-2.0 |
def raw_data_keys(d):
"""
Validate raw dictionary, no top-level keys with leading underscores,
except for _module, and no keys with double underscores anywhere
"""
keys_all = get_keys_for_dict(d)
errors = []
try:
no_double_underscores(keys_all)
except ValueError as e:
er... |
Validate raw dictionary, no top-level keys with leading underscores,
except for _module, and no keys with double underscores anywhere
| raw_data_keys | python | ploomber/ploomber | src/ploomber/env/validate.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/validate.py | Apache-2.0 |
def get_keys_for_dict(d):
"""
Get all (possibly nested) keys in a dictionary
"""
out = []
for k, v in d.items():
out.append(k)
if isinstance(v, Mapping):
out += get_keys_for_dict(v)
return out |
Get all (possibly nested) keys in a dictionary
| get_keys_for_dict | python | ploomber/ploomber | src/ploomber/env/validate.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/env/validate.py | Apache-2.0 |
def next_task():
"""
Return the next Task to execute, returns None if no Tasks are
available for execution (cause their dependencies are not done yet)
and raises a StopIteration exception if there are no more tasks to
run, which means the DAG is done
... |
Return the next Task to execute, returns None if no Tasks are
available for execution (cause their dependencies are not done yet)
and raises a StopIteration exception if there are no more tasks to
run, which means the DAG is done
| next_task | python | ploomber/ploomber | src/ploomber/executors/parallel.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/executors/parallel.py | Apache-2.0 |
def catch_warnings(fn, warnings_all):
"""
Catch all warnings on the current task (except DeprecationWarning)
and append them to warnings_all. Runs if the parameter catch_warnings
is true.
Parameters
----------
fn : function
A LazyFunction that automatically calls catch_warnings, wit... |
Catch all warnings on the current task (except DeprecationWarning)
and append them to warnings_all. Runs if the parameter catch_warnings
is true.
Parameters
----------
fn : function
A LazyFunction that automatically calls catch_warnings, with parameters
from the main function (... | catch_warnings | python | ploomber/ploomber | src/ploomber/executors/serial.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/executors/serial.py | Apache-2.0 |
def catch_exceptions(fn, exceptions_all):
"""
If there is an exception, log it and append it to warnings_all. Runs if
the parameter catch_exceptions is true.
Parameters
----------
fn : function
A LazyFunction that automatically calls catch_exceptions, with
parameters from the ma... |
If there is an exception, log it and append it to warnings_all. Runs if
the parameter catch_exceptions is true.
Parameters
----------
fn : function
A LazyFunction that automatically calls catch_exceptions, with
parameters from the main function (exceptions_all) and the
curr... | catch_exceptions | python | ploomber/ploomber | src/ploomber/executors/serial.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/executors/serial.py | Apache-2.0 |
def pass_exceptions(fn):
"""
Pass all exceptions for the current task and nothing. Runs if
both parameters catch_exceptions and catch_warnings are false.
Parameters
----------
fn : function
A LazyFunction that automatically calls pass_exceptions on the
current scheduled task.
... |
Pass all exceptions for the current task and nothing. Runs if
both parameters catch_exceptions and catch_warnings are false.
Parameters
----------
fn : function
A LazyFunction that automatically calls pass_exceptions on the
current scheduled task.
| pass_exceptions | python | ploomber/ploomber | src/ploomber/executors/serial.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/executors/serial.py | Apache-2.0 |
def build_in_subprocess(task, build_kwargs, reports_all):
"""
Execute the current task in a subprocess. Runs if the parameter
build_in_subprocess is true.
Parameters
----------
task : DAG object
The current task.
build_kwargs: dict
Contains bool catch_exceptions and bool ca... |
Execute the current task in a subprocess. Runs if the parameter
build_in_subprocess is true.
Parameters
----------
task : DAG object
The current task.
build_kwargs: dict
Contains bool catch_exceptions and bool catch_warnings, checks
whether to catch exceptions and warn... | build_in_subprocess | python | ploomber/ploomber | src/ploomber/executors/serial.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/executors/serial.py | Apache-2.0 |
def exception(exc):
"""Formats an exception into a more concise traceback
Parameters
----------
"""
# extract all the exception objects, in case this is a chained exception
exceptions = [exc]
while exc.__cause__:
exceptions.append(exc.__cause__)
exc = exc.__cause__
# ... | Formats an exception into a more concise traceback
Parameters
----------
| exception | python | ploomber/ploomber | src/ploomber/executors/_format.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/executors/_format.py | Apache-2.0 |
def serializer(extension_mapping=None, *, fallback=False, defaults=None, unpack=False):
"""Decorator for serializing functions
Parameters
----------
extension_mapping : dict, default=None
An extension -> function mapping. Calling the decorated function with a
File of a given extension w... | Decorator for serializing functions
Parameters
----------
extension_mapping : dict, default=None
An extension -> function mapping. Calling the decorated function with a
File of a given extension will use the one in the mapping if it exists,
e.g., {'.csv': to_csv, '.json': to_json}.
... | serializer | python | ploomber/ploomber | src/ploomber/io/serialize.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/serialize.py | Apache-2.0 |
def _serialize_product(
obj, product, extension_mapping, fallback, serializer_fallback, fn, unpack
):
"""
Determine which function to use for serialization. Note that this
function operates on single products. If the task generates multiple
products, this function is called multiple times.
"""
... |
Determine which function to use for serialization. Note that this
function operates on single products. If the task generates multiple
products, this function is called multiple times.
| _serialize_product | python | ploomber/ploomber | src/ploomber/io/serialize.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/serialize.py | Apache-2.0 |
def _write_source(
self, lines: Sequence[str], indents: Sequence[str] = (), lexer: str = "pytb"
) -> None:
"""Write lines of source code possibly highlighted.
Keeping this private for now because the API is clunky.
We should discuss how
to evolve the terminal writer so we ca... | Write lines of source code possibly highlighted.
Keeping this private for now because the API is clunky.
We should discuss how
to evolve the terminal writer so we can have more precise color
support, for example
being able to write part of a line in one color and the rest in
... | _write_source | python | ploomber/ploomber | src/ploomber/io/terminalwriter.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/terminalwriter.py | Apache-2.0 |
def _highlight(self, source: str, lexer: str) -> str:
"""Highlight the given source code if we have markup support."""
if lexer not in {"py", "pytb"}:
raise ValueError(f'lexer must be "py" or "pytb", got: {lexer!r}')
if not self.hasmarkup or not self.code_highlight:
retu... | Highlight the given source code if we have markup support. | _highlight | python | ploomber/ploomber | src/ploomber/io/terminalwriter.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/terminalwriter.py | Apache-2.0 |
def unserializer(
extension_mapping=None, *, fallback=False, defaults=None, unpack=False
):
"""Decorator for unserializing functions
Parameters
----------
extension_mapping : dict, default=None
An extension -> function mapping. Calling the decorated function with a
File of a given e... | Decorator for unserializing functions
Parameters
----------
extension_mapping : dict, default=None
An extension -> function mapping. Calling the decorated function with a
File of a given extension will use the one in the mapping if it exists,
e.g., {'.csv': from_csv, '.json': from_j... | unserializer | python | ploomber/ploomber | src/ploomber/io/unserialize.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/unserialize.py | Apache-2.0 |
def wcwidth(c: str) -> int:
"""Determine how many columns are needed to display a character in a
terminal. Returns -1 if the character is not printable.
Returns 0, 1 or 2 for other characters.
"""
o = ord(c)
# ASCII fast path.
if 0x20 <= o < 0x07F:
return 1
# Some Cf/Zp/Zl char... | Determine how many columns are needed to display a character in a
terminal. Returns -1 if the character is not printable.
Returns 0, 1 or 2 for other characters.
| wcwidth | python | ploomber/ploomber | src/ploomber/io/wcwidth.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/wcwidth.py | Apache-2.0 |
def wcswidth(s: str) -> int:
"""Determine how many columns are needed to display a string in a terminal.
Returns -1 if the string contains non-printable characters.
"""
width = 0
for c in unicodedata.normalize("NFC", s):
wc = wcwidth(c)
if wc < 0:
return -1
width ... | Determine how many columns are needed to display a string in a terminal.
Returns -1 if the string contains non-printable characters.
| wcswidth | python | ploomber/ploomber | src/ploomber/io/wcwidth.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/wcwidth.py | Apache-2.0 |
def run(
self,
*cmd,
description=None,
capture_output=False,
expected_output=None,
error_message=None,
hint=None,
show_cmd=True,
):
"""Execute a command in a subprocess
Parameters
----------
*cmd
Command to ... | Execute a command in a subprocess
Parameters
----------
*cmd
Command to execute
description: str, default=None
Label to display before executing the command
capture_output: bool, default=False
Captures output, otherwise prints to standard ou... | run | python | ploomber/ploomber | src/ploomber/io/_commander.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/_commander.py | Apache-2.0 |
def copy_template(self, path, **render_kwargs):
"""Copy template to the workspace
Parameters
----------
path : str
Path to template (relative to templates path)
**render_kwargs
Keyword arguments passed to the template
Examples
--------
... | Copy template to the workspace
Parameters
----------
path : str
Path to template (relative to templates path)
**render_kwargs
Keyword arguments passed to the template
Examples
--------
>>> # copies template in {templates-path}/directory/... | copy_template | python | ploomber/ploomber | src/ploomber/io/_commander.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/_commander.py | Apache-2.0 |
def cp(self, src):
"""
Copies a file or directory to the workspace, replacing it if necessary.
Deleted on exit.
Notes
-----
Used mainly for preparing Dockerfiles since they can only
copy from the current working directory
Examples
--------
... |
Copies a file or directory to the workspace, replacing it if necessary.
Deleted on exit.
Notes
-----
Used mainly for preparing Dockerfiles since they can only
copy from the current working directory
Examples
--------
>>> # copies dir/file to {wo... | cp | python | ploomber/ploomber | src/ploomber/io/_commander.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/_commander.py | Apache-2.0 |
def append_inline(self, line, dst):
"""Append line to a file
Parameters
----------
line : str
Line to append
dst : str
File to append (can be outside the workspace)
Examples
--------
>>> cmdr.append_inline('*.csv', '.gitignore') ... | Append line to a file
Parameters
----------
line : str
Line to append
dst : str
File to append (can be outside the workspace)
Examples
--------
>>> cmdr.append_inline('*.csv', '.gitignore') # doctest: +SKIP
| append_inline | python | ploomber/ploomber | src/ploomber/io/_commander.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/_commander.py | Apache-2.0 |
def _warn_show(self):
"""Display accumulated warning messages (added via .warn_on_exit)"""
if self._warnings:
self.tw.sep("=", "Warnings", yellow=True)
self.tw.write("\n\n".join(self._warnings) + "\n")
self.tw.sep("=", yellow=True) | Display accumulated warning messages (added via .warn_on_exit) | _warn_show | python | ploomber/ploomber | src/ploomber/io/_commander.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/io/_commander.py | Apache-2.0 |
def remove_line_number(path):
"""
Takes a path/to/file:line path and returns path/to/file path object
"""
parts = list(Path(path).parts)
parts[-1] = parts[-1].split(":")[0]
return Path(*parts) |
Takes a path/to/file:line path and returns path/to/file path object
| remove_line_number | python | ploomber/ploomber | src/ploomber/jupyter/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/dag.py | Apache-2.0 |
def overwrite(self, model, path):
"""Overwrite a model back to the original function"""
resource = self._get(path)
resource.interactive.overwrite(nbformat.from_dict(model["content"]))
return {
"name": resource.task.name,
"type": "notebook",
"path": p... | Overwrite a model back to the original function | overwrite | python | ploomber/ploomber | src/ploomber/jupyter/dag.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/dag.py | Apache-2.0 |
def _mapping(self):
"""Returns the corresponding DAGMapping instance for the current DAG"""
if self.__mapping is None:
notebook_tasks = [
task for task in self._dag.values() if isinstance(task, NotebookMixin)
]
pairs = [
(resolve_path(... | Returns the corresponding DAGMapping instance for the current DAG | _mapping | python | ploomber/ploomber | src/ploomber/jupyter/manager.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/manager.py | Apache-2.0 |
def resolve_path(parent, path):
"""
Functions functions resolves paths to make the {source} -> {task} mapping
work even then `jupyter notebook` is initialized from a subdirectory
of pipeline.yaml
"""
try:
# FIXME: remove :linenumber
return Path(path).resolve().relative_to(parent)... |
Functions functions resolves paths to make the {source} -> {task} mapping
work even then `jupyter notebook` is initialized from a subdirectory
of pipeline.yaml
| resolve_path | python | ploomber/ploomber | src/ploomber/jupyter/manager.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/manager.py | Apache-2.0 |
def __init__(self, *args, **kwargs):
"""
Initialize the content manger, look for a pipeline.yaml file in the
current directory, if there is one, load it, if there isn't one
don't do anything
"""
# NOTE: there is some strange behavior in the Jupyter... |
Initialize the content manger, look for a pipeline.yaml file in the
current directory, if there is one, load it, if there isn't one
don't do anything
| __init__ | python | ploomber/ploomber | src/ploomber/jupyter/manager.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/manager.py | Apache-2.0 |
def get(self, path, content=True, type=None, format=None, *args, **kwargs):
"""
This is called when opening a file (content=True) and when listing
files. When listing it's called once per file with (content=False).
Also called for directories. When the directory is part ... |
This is called when opening a file (content=True) and when listing
files. When listing it's called once per file with (content=False).
Also called for directories. When the directory is part of the
listing (content=False) and when opened (content=True)
| get | python | ploomber/ploomber | src/ploomber/jupyter/manager.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/manager.py | Apache-2.0 |
def save(self, model, path=""):
"""
This is called when a file is saved
"""
if self.manager and path in self.manager:
out = self.manager.overwrite(model, path)
return out
else:
check_metadata_filter(self.log, mod... |
This is called when a file is saved
| save | python | ploomber/ploomber | src/ploomber/jupyter/manager.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/manager.py | Apache-2.0 |
def _model_in_dag(self, model, path=None):
"""Determine if the model is part of the pipeline"""
model_in_dag = False
if path is None:
path = model["path"]
else:
path = path.strip("/")
if self.dag:
if "content"... | Determine if the model is part of the pipeline | _model_in_dag | python | ploomber/ploomber | src/ploomber/jupyter/manager.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/manager.py | Apache-2.0 |
def _load_jupyter_server_extension(app):
"""
This function is called to configure the new content manager, there are a
lot of quirks that jupytext maintainers had to solve to make it work so
we base our implementation on theirs:
https://github.com/mwouts/jupytext/blob/bc1b15935e096c280b6630f45e65c33... |
This function is called to configure the new content manager, there are a
lot of quirks that jupytext maintainers had to solve to make it work so
we base our implementation on theirs:
https://github.com/mwouts/jupytext/blob/bc1b15935e096c280b6630f45e65c331f04f7d9c/jupytext/__init__.py#L19
| _load_jupyter_server_extension | python | ploomber/ploomber | src/ploomber/jupyter/manager.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/jupyter/manager.py | Apache-2.0 |
def grid(**params):
"""A decorator to create multiple tasks, one per parameter combination"""
def decorator(f):
if not hasattr(f, "__ploomber_grid__"):
f.__ploomber_grid__ = []
# TODO: validate they have the same keys as the earlier ones
f.__ploomber_grid__.append(params)
... | A decorator to create multiple tasks, one per parameter combination | grid | python | ploomber/ploomber | src/ploomber/micro/_micro.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/micro/_micro.py | Apache-2.0 |
def capture(f):
"""A decorator to capture outputs in a function"""
f.__ploomber_capture__ = True
f.__ploomber_globals__ = f.__globals__
return f | A decorator to capture outputs in a function | capture | python | ploomber/ploomber | src/ploomber/micro/_micro.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/micro/_micro.py | Apache-2.0 |
def _signature_wrapper(f, call_with_args):
"""An internal wrapper so functions don't need the upstream and product
arguments
"""
# store the wrapper, we'll need this for hot_reload to work, see
# the constructor of CallableLoader in
# ploomber.sources.pythoncallablesource for details
f.__plo... | An internal wrapper so functions don't need the upstream and product
arguments
| _signature_wrapper | python | ploomber/ploomber | src/ploomber/micro/_micro.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/micro/_micro.py | Apache-2.0 |
def _get_upstream(fn):
"""
Get upstream tasks for a given function by looking at the signature
arguments
"""
if hasattr(fn, "__wrapped__"):
grid = getattr(fn, "__ploomber_grid__", None)
if grid is not None:
ignore = set(grid[0])
else:
ignore = set()
... |
Get upstream tasks for a given function by looking at the signature
arguments
| _get_upstream | python | ploomber/ploomber | src/ploomber/micro/_micro.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/micro/_micro.py | Apache-2.0 |
def dag_from_functions(
functions,
output="output",
params=None,
parallel=False,
dependencies=None,
hot_reload=True,
):
"""Create a DAG from a list of functions
Parameters
----------
functions : list
List of functions
output : str, default='output'
Directory... | Create a DAG from a list of functions
Parameters
----------
functions : list
List of functions
output : str, default='output'
Directory to store outputs and metadata from each task
params : dict, default None
Parameters to pass to each task, it must be a dictionary with ta... | dag_from_functions | python | ploomber/ploomber | src/ploomber/micro/_micro.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/micro/_micro.py | Apache-2.0 |
def _raw(self):
"""A string with the raw jinja2.Template contents"""
if self._hot_reload:
self.__raw = self._path.read_text()
return self.__raw | A string with the raw jinja2.Template contents | _raw | python | ploomber/ploomber | src/ploomber/placeholders/placeholder.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/placeholder.py | Apache-2.0 |
def _needs_render(self):
"""
Returns true if the template is a literal and does not need any
parameters to render
"""
env = self._template.environment
# check if the template has the variable or block start string
# is there any better way of checking this?
... |
Returns true if the template is a literal and does not need any
parameters to render
| _needs_render | python | ploomber/ploomber | src/ploomber/placeholders/placeholder.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/placeholder.py | Apache-2.0 |
def best_repr(self, shorten):
"""
Returns the rendered version (if available), otherwise the raw version
"""
best = self._raw if self._str is None else self._str
if shorten:
best = self._repr.repr(best)
return best |
Returns the rendered version (if available), otherwise the raw version
| best_repr | python | ploomber/ploomber | src/ploomber/placeholders/placeholder.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/placeholder.py | Apache-2.0 |
def variables(self):
"""Returns declared variables in the template"""
# this requires parsing the raw template, do lazy load, but override
# it if hot_reload is True
if self._variables is None or self._hot_reload:
self._variables = util.get_tags_in_str(self._raw)
ret... | Returns declared variables in the template | variables | python | ploomber/ploomber | src/ploomber/placeholders/placeholder.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/placeholder.py | Apache-2.0 |
def _init_template(raw, loader_init):
"""
Initializes template, taking care of configuring the loader environment
if needed
This helps prevents errors when using copy or pickling (the copied or
unpickled object wont have access to the environment.loader which breaks
macros and anything that nee... |
Initializes template, taking care of configuring the loader environment
if needed
This helps prevents errors when using copy or pickling (the copied or
unpickled object wont have access to the environment.loader which breaks
macros and anything that needs access to the jinja environment.loader
... | _init_template | python | ploomber/ploomber | src/ploomber/placeholders/placeholder.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/placeholder.py | Apache-2.0 |
def get(self, key):
"""Load template, returns None if it doesn' exist"""
try:
return self[key]
except exceptions.TemplateNotFound:
return None | Load template, returns None if it doesn' exist | get | python | ploomber/ploomber | src/ploomber/placeholders/sourceloader.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/sourceloader.py | Apache-2.0 |
def path_to(self, key):
"""Return the path to a template, even if it doesn't exist"""
try:
return self[key].path
except exceptions.TemplateNotFound:
return Path(self.path_full, key) | Return the path to a template, even if it doesn't exist | path_to | python | ploomber/ploomber | src/ploomber/placeholders/sourceloader.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/sourceloader.py | Apache-2.0 |
def get_template(self, name):
"""Load a template by name
Parameters
----------
name : str or pathlib.Path
Template to load
"""
# if name is a nested path, this will return an appropriate
# a/b/c string even on Windows
path = str(PurePosixPath(... | Load a template by name
Parameters
----------
name : str or pathlib.Path
Template to load
| get_template | python | ploomber/ploomber | src/ploomber/placeholders/sourceloader.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/sourceloader.py | Apache-2.0 |
def get_tags_in_str(s, require_runtime_placeholders=True):
"""
Returns tags (e.g. {{variable}}) in a given string as a set, returns an
empty set for None
Parameters
----------
require_runtime_placeholders : bool, default=True
Also check runtime tags - the ones in square brackets
... |
Returns tags (e.g. {{variable}}) in a given string as a set, returns an
empty set for None
Parameters
----------
require_runtime_placeholders : bool, default=True
Also check runtime tags - the ones in square brackets
(e.g. [[placeholder]])
| get_tags_in_str | python | ploomber/ploomber | src/ploomber/placeholders/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/placeholders/util.py | Apache-2.0 |
def _check_is_outdated(self, outdated_by_code):
"""
Unlike other Product implementation that only have to check the
current metadata, File has to check if there is a metadata remote copy
and download it to decide outdated status, which yield to task
execution or product downloadi... |
Unlike other Product implementation that only have to check the
current metadata, File has to check if there is a metadata remote copy
and download it to decide outdated status, which yield to task
execution or product downloading
| _check_is_outdated | python | ploomber/ploomber | src/ploomber/products/file.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/file.py | Apache-2.0 |
def _is_remote_outdated(self, outdated_by_code):
"""
Check status using remote metadata, if no remote is available
(or remote metadata is corrupted) returns True
"""
if self._remote.exists():
return self._remote._is_outdated(
with_respect_to_local=Fals... |
Check status using remote metadata, if no remote is available
(or remote metadata is corrupted) returns True
| _is_remote_outdated | python | ploomber/ploomber | src/ploomber/products/file.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/file.py | Apache-2.0 |
def _get(self):
"""
Get the "true metadata", ignores actual metadata if the product does
not exist. It is lazily called by the timestamp and stored_source_code
attributes. Ignores fetched metadata and replaces it with the stored
metadata
"""
# if the product does ... |
Get the "true metadata", ignores actual metadata if the product does
not exist. It is lazily called by the timestamp and stored_source_code
attributes. Ignores fetched metadata and replaces it with the stored
metadata
| _get | python | ploomber/ploomber | src/ploomber/products/metadata.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/metadata.py | Apache-2.0 |
def update(self, source_code, params):
"""
Update metadata in the storage backend, this should be called by
Task objects when running successfully to update metadata in the
backend storage. If saving in the backend storage succeeds the local
copy is updated as well
Param... |
Update metadata in the storage backend, this should be called by
Task objects when running successfully to update metadata in the
backend storage. If saving in the backend storage succeeds the local
copy is updated as well
Parameters
----------
source_code : str... | update | python | ploomber/ploomber | src/ploomber/products/metadata.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/metadata.py | Apache-2.0 |
def update_locally(self, data):
"""Updates the in-memory copy, does not update persistent copy"""
# could be the case that we haven't fetched metadata yet. since this
# overwrites existing metadata. we no longer have to fetch
self._did_fetch = True
self._data = deepcopy(data) | Updates the in-memory copy, does not update persistent copy | update_locally | python | ploomber/ploomber | src/ploomber/products/metadata.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/metadata.py | Apache-2.0 |
def clear(self):
"""
Clears up metadata local copy, next time the timestamp or
stored_source_code are needed, this will trigger another call to
._get(). Should be called only when the local copy might be outdated
due external execution. Currently, we are only using this when runn... |
Clears up metadata local copy, next time the timestamp or
stored_source_code are needed, this will trigger another call to
._get(). Should be called only when the local copy might be outdated
due external execution. Currently, we are only using this when running
DAG.build_partia... | clear | python | ploomber/ploomber | src/ploomber/products/metadata.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/metadata.py | Apache-2.0 |
def large_timestamp_difference(timestamps):
"""Returns True if there is at least one timestamp difference > 5 seconds"""
dts = [datetime.fromtimestamp(ts) for ts in timestamps]
for i in range(len(dts)):
for j in range(len(dts)):
if i != j:
diff = (dts[i] - dts[j]).total_... | Returns True if there is at least one timestamp difference > 5 seconds | large_timestamp_difference | python | ploomber/ploomber | src/ploomber/products/metadata.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/metadata.py | Apache-2.0 |
def to_json_serializable(self):
"""Returns a JSON serializable version of this product"""
if isinstance(self.products, Mapping):
return {name: str(product) for name, product in self.products.items()}
else:
return list(str(product) for product in self.products) | Returns a JSON serializable version of this product | to_json_serializable | python | ploomber/ploomber | src/ploomber/products/metaproduct.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/metaproduct.py | Apache-2.0 |
def _is_outdated(self, outdated_by_code=True):
"""
Given current conditions, determine if the Task that holds this
Product should be executed
Returns
-------
bool
True if the Task should execute
"""
# if hot_reload is enable, we should not cac... |
Given current conditions, determine if the Task that holds this
Product should be executed
Returns
-------
bool
True if the Task should execute
| _is_outdated | python | ploomber/ploomber | src/ploomber/products/product.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/product.py | Apache-2.0 |
def _outdated_data_dependencies(self):
"""
Determine if the product is outdated by checking upstream timestamps
"""
if self._outdated_data_dependencies_status is not None:
self.logger.debug(
("Returning cached data dependencies status. " "Outdated? %s"),
... |
Determine if the product is outdated by checking upstream timestamps
| _outdated_data_dependencies | python | ploomber/ploomber | src/ploomber/products/product.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/product.py | Apache-2.0 |
def _is_outdated_due_to_upstream(self, up_prod):
"""
A task becomes data outdated if an upstream product has a higher
timestamp or if an upstream product is outdated
"""
if self.metadata.timestamp is None or up_prod.metadata.timestamp is None:
return True
else... |
A task becomes data outdated if an upstream product has a higher
timestamp or if an upstream product is outdated
| _is_outdated_due_to_upstream | python | ploomber/ploomber | src/ploomber/products/product.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/product.py | Apache-2.0 |
def _outdated_code_dependency(self):
"""
Determine if the product is outdated by checking the source code that
it generated it
"""
if self._outdated_code_dependency_status is not None:
self.logger.debug(
("Returning cached code dependencies status. " "... |
Determine if the product is outdated by checking the source code that
it generated it
| _outdated_code_dependency | python | ploomber/ploomber | src/ploomber/products/product.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/product.py | Apache-2.0 |
def remove_non_serializable_top_keys(obj):
"""
Remove top-level keys with unserializable objects, warning if necessary
Parameters
----------
d: a dictionary containing parameters
"""
out = copy(obj)
for _, _, current_val, preffix in iterate_nested_dict(obj):
if not is_json_seri... |
Remove top-level keys with unserializable objects, warning if necessary
Parameters
----------
d: a dictionary containing parameters
| remove_non_serializable_top_keys | python | ploomber/ploomber | src/ploomber/products/serializeparams.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/serializeparams.py | Apache-2.0 |
def exists(self):
"""
Checks if remote File exists. This is used by Metadata to determine
whether to use the existing remote metadat (if any) or ignore it: if
this returns False, remote metadata is ignored even if it exists
"""
if self._exists is None:
# TODO ... |
Checks if remote File exists. This is used by Metadata to determine
whether to use the existing remote metadat (if any) or ignore it: if
this returns False, remote metadata is ignored even if it exists
| exists | python | ploomber/ploomber | src/ploomber/products/_remotefile.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/_remotefile.py | Apache-2.0 |
def _is_outdated(self, with_respect_to_local, outdated_by_code=True):
"""
Determines outdated status using remote metadata, to decide
whether to download the remote file or not
with_respect_to_local : bool
If True, determines status by comparing timestamps with upstream
... |
Determines outdated status using remote metadata, to decide
whether to download the remote file or not
with_respect_to_local : bool
If True, determines status by comparing timestamps with upstream
local metadata, otherwise it uses upstream remote metadata
| _is_outdated | python | ploomber/ploomber | src/ploomber/products/_remotefile.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/_remotefile.py | Apache-2.0 |
def _outdated_code_dependency(self):
"""
Determine if the source code has changed by looking at the remote
metadata
"""
outdated, _ = self._local_file.task.dag.differ.is_different(
a=self.metadata.stored_source_code,
b=str(self._local_file.task.source),
... |
Determine if the source code has changed by looking at the remote
metadata
| _outdated_code_dependency | python | ploomber/ploomber | src/ploomber/products/_remotefile.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/_remotefile.py | Apache-2.0 |
def process_resources(params):
"""
Process resources in a parameters dict, computes the hash of the file for
resources (i.e., params with the resource__ prefix)
Parameters
----------
params : dict
Task parameters
"""
# params can be None
if params is None:
return No... |
Process resources in a parameters dict, computes the hash of the file for
resources (i.e., params with the resource__ prefix)
Parameters
----------
params : dict
Task parameters
| process_resources | python | ploomber/ploomber | src/ploomber/products/_resources.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/products/_resources.py | Apache-2.0 |
def create(self, source, params, class_):
"""Scaffold a task if they don't exist
Returns
-------
bool
True if it created a task, False if it didn't
"""
did_create = False
if class_ is tasks.PythonCallable:
source_parts = source.split(".")... | Scaffold a task if they don't exist
Returns
-------
bool
True if it created a task, False if it didn't
| create | python | ploomber/ploomber | src/ploomber/scaffold/scaffoldloader.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/scaffold/scaffoldloader.py | Apache-2.0 |
def getfile(fn):
"""
Returns the file where the function is defined. Works even in wrapped
functions
"""
if hasattr(fn, "__wrapped__"):
return getfile(fn.__wrapped__)
else:
return inspect.getfile(fn) |
Returns the file where the function is defined. Works even in wrapped
functions
| getfile | python | ploomber/ploomber | src/ploomber/sources/inspect.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/inspect.py | Apache-2.0 |
def to_nb(self, path=None):
"""
Converts the function to is notebook representation, Returns a
notebook object, if path is passed, it saves the notebook as well
Returns the function's body in a notebook (tmp location), inserts
params as variables at the top
"""
se... |
Converts the function to is notebook representation, Returns a
notebook object, if path is passed, it saves the notebook as well
Returns the function's body in a notebook (tmp location), inserts
params as variables at the top
| to_nb | python | ploomber/ploomber | src/ploomber/sources/interact.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/interact.py | Apache-2.0 |
def overwrite(self, obj):
"""
Overwrite the function's body with the notebook contents, excluding
injected parameters and cells whose first line is "#". obj can be
either a notebook object or a path
"""
self._reload_fn()
if isinstance(obj, (str, Path)):
... |
Overwrite the function's body with the notebook contents, excluding
injected parameters and cells whose first line is "#". obj can be
either a notebook object or a path
| overwrite | python | ploomber/ploomber | src/ploomber/sources/interact.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/interact.py | Apache-2.0 |
def last_non_empty_cell(cells):
"""Returns the index + 1 for the last non-empty cell"""
idx = len(cells)
for cell in cells[::-1]:
if cell.source:
return idx
idx -= 1
return idx | Returns the index + 1 for the last non-empty cell | last_non_empty_cell | python | ploomber/ploomber | src/ploomber/sources/interact.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/interact.py | Apache-2.0 |
def keep_cell(cell):
"""
Rule to decide whether to keep a cell or not. This is executed before
converting the notebook back to a function
"""
cell_tags = set(cell["metadata"].get("tags", {}))
# remove cell with this tag, they are not part of the function body
tags_to_remove = {
"inj... |
Rule to decide whether to keep a cell or not. This is executed before
converting the notebook back to a function
| keep_cell | python | ploomber/ploomber | src/ploomber/sources/interact.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/interact.py | Apache-2.0 |
def parse_function(fn):
"""
Extract function's source code, parse it and return function body
elements along with the # of the last line for the signature (which
marks the beginning of the function's body) and all the imports
"""
# TODO: exclude return at the end, what if we find more than one?
... |
Extract function's source code, parse it and return function body
elements along with the # of the last line for the signature (which
marks the beginning of the function's body) and all the imports
| parse_function | python | ploomber/ploomber | src/ploomber/sources/interact.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/interact.py | Apache-2.0 |
def has_import(stmt):
"""
Check if statement contains an import
"""
for ch in stmt.children:
if ch.type in {"import_name", "import_from"}:
return True
return False |
Check if statement contains an import
| has_import | python | ploomber/ploomber | src/ploomber/sources/interact.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/interact.py | Apache-2.0 |
def function_to_nb(
body_elements, imports_top, imports_local, imports_bottom, params, fn, path
):
"""
Save function body elements to a notebook
"""
# TODO: Params should implement an option to call to_json_serializable
# on product to avoid repetition I'm using this same code in notebook
# ... |
Save function body elements to a notebook
| function_to_nb | python | ploomber/ploomber | src/ploomber/sources/interact.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/sources/interact.py | Apache-2.0 |
def find_cell_with_tags(nb, tags):
"""
Find the first cell with any of the given tags, returns a dictionary
with 'cell' (cell object) and 'index', the cell index.
"""
tags_to_find = list(tags)
tags_found = {}
for index, cell in enumerate(nb["cells"]):
for tag in cell["metadata"].get... |
Find the first cell with any of the given tags, returns a dictionary
with 'cell' (cell object) and 'index', the cell index.
| find_cell_with_tags | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.