code
large_stringlengths
52
373k
docstring
large_stringlengths
3
47.2k
language
large_stringclasses
6 values
def invoke_step(self, context): """Invoke 'run_step' in the dynamically loaded step module. Don't invoke this from outside the Step class. Use pypyr.dsl.Step.run_step instead. invoke_step just does the bare module step invocation, it does not evaluate any of the decorator logic ...
Invoke 'run_step' in the dynamically loaded step module. Don't invoke this from outside the Step class. Use pypyr.dsl.Step.run_step instead. invoke_step just does the bare module step invocation, it does not evaluate any of the decorator logic surrounding the step. So unless you...
python
def run_conditional_decorators(self, context): """Evaluate the step decorators to decide whether to run step or not. Use pypyr.dsl.Step.run_step if you intend on executing the step the same way pypyr does. Args: context: (pypyr.context.Context) The pypyr context. This arg w...
Evaluate the step decorators to decide whether to run step or not. Use pypyr.dsl.Step.run_step if you intend on executing the step the same way pypyr does. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
python
def run_foreach_or_conditional(self, context): """Run the foreach sequence or the conditional evaluation. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate. """ logger.debug("starting") # friendly reminder [] list obj...
Run the foreach sequence or the conditional evaluation. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
python
def run_step(self, context): """Run a single pipeline step. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate. """ logger.debug("starting") # the in params should be added to context before step execution. sel...
Run a single pipeline step. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
python
def set_step_input_context(self, context): """Append step's 'in' parameters to context, if they exist. Append the[in] dictionary to the context. This will overwrite existing values if the same keys are already in there. I.e if in_parameters has {'eggs': 'boiled'} and key 'eggs' already ...
Append step's 'in' parameters to context, if they exist. Append the[in] dictionary to the context. This will overwrite existing values if the same keys are already in there. I.e if in_parameters has {'eggs': 'boiled'} and key 'eggs' already exists in context, context['eggs'] hereafter w...
python
def exec_iteration(self, counter, context, step_method): """Run a single retry iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.retry_loop where con...
Run a single retry iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.retry_loop where context and step_method set. while_until_true injects counter a...
python
def retry_loop(self, context, step_method): """Run step inside a retry loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (meth...
Run step inside a retry loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (method/function) This is the method/function that ...
python
def exec_iteration(self, counter, context, step_method): """Run a single loop iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.while_loop where cont...
Run a single loop iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.while_loop where context and step_method set. while_until_true injects counter as...
python
def while_loop(self, context, step_method): """Run step inside a while loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (meth...
Run step inside a while loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (method/function) This is the method/function that ...
python
def run_step(context): """Load a yaml file into the pypyr context. Yaml parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file yaml has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, retur...
Load a yaml file into the pypyr context. Yaml parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file yaml has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, returned context['eggs'] will be 'b...
python
def run_step(context): """pypyr step saves current utc datetime to context. Args: context: pypyr.context.Context. Mandatory. The following context key is optional: - nowUtcIn. str. Datetime formatting expression. For full list of possible expressions, ...
pypyr step saves current utc datetime to context. Args: context: pypyr.context.Context. Mandatory. The following context key is optional: - nowUtcIn. str. Datetime formatting expression. For full list of possible expressions, check here: ...
python
def run_step(context): """Assert that something is True or equal to something else. Args: context: dictionary-like pypyr.context.Context. context is mandatory. Uses the following context keys in context: - assert - this. mandatory. Any type. If assert['equals'] not s...
Assert that something is True or equal to something else. Args: context: dictionary-like pypyr.context.Context. context is mandatory. Uses the following context keys in context: - assert - this. mandatory. Any type. If assert['equals'] not specified, ev...
python
def tar_archive(context): """Archive specified path to a tar archive. Args: context: dictionary-like. context is mandatory. context['tar']['archive'] must exist. It's a dictionary. keys are the paths to archive. values are the destination output paths. Example: ...
Archive specified path to a tar archive. Args: context: dictionary-like. context is mandatory. context['tar']['archive'] must exist. It's a dictionary. keys are the paths to archive. values are the destination output paths. Example: tar: archive:...
python
def tar_extract(context): """Extract all members of tar archive to specified path. Args: context: dictionary-like. context is mandatory. context['tar']['extract'] must exist. It's a dictionary. keys are the path to the tar to extract. values are the destination paths...
Extract all members of tar archive to specified path. Args: context: dictionary-like. context is mandatory. context['tar']['extract'] must exist. It's a dictionary. keys are the path to the tar to extract. values are the destination paths. Example: tar: ...
python
def run_step(context): """Run shell command without shell interpolation. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execu...
Run shell command without shell interpolation. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execute. save: bool. defaul...
python
def get_args(get_item): """Parse env, key, default out of input dict. Args: get_item: dict. contains keys env/key/default Returns: (env, key, has_default, default) tuple, where env: str. env var name. key: str. save env value to this context key. has_def...
Parse env, key, default out of input dict. Args: get_item: dict. contains keys env/key/default Returns: (env, key, has_default, default) tuple, where env: str. env var name. key: str. save env value to this context key. has_default: bool. True if default spe...
python
def run_step(context): """Executes dynamic python code. Context is a dictionary or dictionary-like. Context must contain key 'pycode' Will exec context['pycode'] as dynamically interpreted python statements. context is mandatory. When you execute the pipeline, it should look something like thi...
Executes dynamic python code. Context is a dictionary or dictionary-like. Context must contain key 'pycode' Will exec context['pycode'] as dynamically interpreted python statements. context is mandatory. When you execute the pipeline, it should look something like this: pipeline-runner [na...
python
def get_parser(): """Return ArgumentParser for pypyr cli.""" parser = argparse.ArgumentParser( allow_abbrev=True, description='pypyr pipeline runner') parser.add_argument('pipeline_name', help='Name of pipeline to run. It should exist in the ' ...
Return ArgumentParser for pypyr cli.
python
def main(args=None): """Entry point for pypyr cli. The setup_py entry_point wraps this in sys.exit already so this effectively becomes sys.exit(main()). The __main__ entry point similarly wraps sys.exit(). """ if args is None: args = sys.argv[1:] parsed_args = get_args(args) t...
Entry point for pypyr cli. The setup_py entry_point wraps this in sys.exit already so this effectively becomes sys.exit(main()). The __main__ entry point similarly wraps sys.exit().
python
def run_step(context): """Remove specified keys from context. Args: Context is a dictionary or dictionary-like. context['contextClear'] must exist. It's a dictionary. Will iterate context['contextClear'] and remove those keys from context. For example, say input context is:...
Remove specified keys from context. Args: Context is a dictionary or dictionary-like. context['contextClear'] must exist. It's a dictionary. Will iterate context['contextClear'] and remove those keys from context. For example, say input context is: key1: value1 ...
python
def run_step(context): """Run command, program or executable. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execute. ...
Run command, program or executable. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execute. save: bool. defaults False. s...
python
def run_step(context): """Set hierarchy into context with substitutions if it doesn't exist yet. context is a dictionary or dictionary-like. context['defaults'] must exist. It's a dictionary. Will iterate context['defaults'] and add these as new values where their keys don't already exist. While i...
Set hierarchy into context with substitutions if it doesn't exist yet. context is a dictionary or dictionary-like. context['defaults'] must exist. It's a dictionary. Will iterate context['defaults'] and add these as new values where their keys don't already exist. While it's doing so, it will leave ...
python
def get_pipeline_steps(pipeline, steps_group): """Get the steps attribute of module pipeline. If there is no steps sequence on the pipeline, return None. Guess you could theoretically want to run a pipeline with nothing in it. """ logger.debug("starting") assert pipeline assert steps_group ...
Get the steps attribute of module pipeline. If there is no steps sequence on the pipeline, return None. Guess you could theoretically want to run a pipeline with nothing in it.
python
def run_failure_step_group(pipeline, context): """Run the on_failure step group if it exists. This function will swallow all errors, to prevent obfuscating the error condition that got it here to begin with. """ logger.debug("starting") try: assert pipeline # if no on_failure ex...
Run the on_failure step group if it exists. This function will swallow all errors, to prevent obfuscating the error condition that got it here to begin with.
python
def run_step_group(pipeline_definition, step_group_name, context): """Get the specified step group from the pipeline and run its steps.""" logger.debug(f"starting {step_group_name}") assert step_group_name steps = get_pipeline_steps(pipeline=pipeline_definition, steps_gro...
Get the specified step group from the pipeline and run its steps.
python
def ensure_dir(path): """Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None. """ os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True)
Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None.
python
def get_glob(path): """Process the input path, applying globbing and formatting. Do note that this will returns files AND directories that match the glob. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. Escape all special characters ('?', '*...
Process the input path, applying globbing and formatting. Do note that this will returns files AND directories that match the glob. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. Escape all special characters ('?', '*' and '['). For a literal m...
python
def is_same_file(path1, path2): """Return True if path1 is the same file as path2. The reason for this dance is that samefile throws if either file doesn't exist. Args: path1: str or path-like. path2: str or path-like. Returns: bool. True if the same file, False if not. ...
Return True if path1 is the same file as path2. The reason for this dance is that samefile throws if either file doesn't exist. Args: path1: str or path-like. path2: str or path-like. Returns: bool. True if the same file, False if not.
python
def move_file(src, dest): """Move source file to destination. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. OSError: if any IO ope...
Move source file to destination. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. OSError: if any IO operations go wrong.
python
def move_temp_file(src, dest): """Move src to dest. Delete src if something goes wrong. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. ...
Move src to dest. Delete src if something goes wrong. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. OSError: if any IO operations go w...
python
def files_in_to_out(self, in_path, out_path=None): """Write in files to out, calling the line_handler on each line. Calls file_in_to_out under the hood to format the in_path payload. The formatting processing is done by the self.formatter instance. Args: in_path: str, path-...
Write in files to out, calling the line_handler on each line. Calls file_in_to_out under the hood to format the in_path payload. The formatting processing is done by the self.formatter instance. Args: in_path: str, path-like, or an iterable (list/tuple) of stri...
python
def in_to_out(self, in_path, out_path=None): """Load file into object, formats, writes object to out. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_path, or set it t...
Load file into object, formats, writes object to out. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_path, or set it to None. Args: in_path: str or path-...
python
def in_to_out(self, in_path, out_path=None): """Write a single file in to out, running self.formatter on each line. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_pat...
Write a single file in to out, running self.formatter on each line. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_path, or set it to None. Args: in_path...
python
def dump(self, file, payload): """Dump json oject to open file output. Writes json with 2 spaces indentation. Args: file: Open file-like object. Must be open for writing. payload: The Json object to write to file. Returns: None. """ ...
Dump json oject to open file output. Writes json with 2 spaces indentation. Args: file: Open file-like object. Must be open for writing. payload: The Json object to write to file. Returns: None.
python
def run_step(context): """Parse input file and replace a search string. This also does string substitutions from context on the fileReplacePairs. It does this before it search & replaces the in file. Be careful of order. If fileReplacePairs is not an ordered collection, replacements could evaluate...
Parse input file and replace a search string. This also does string substitutions from context on the fileReplacePairs. It does this before it search & replaces the in file. Be careful of order. If fileReplacePairs is not an ordered collection, replacements could evaluate in any given order. If this i...
python
def set_logging_config(log_level, handlers): """Set python logging library config. Run this ONCE at the start of your process. It formats the python logging module's output. Defaults logging level to INFO = 20) """ logging.basicConfig( format='%(asctime)s %(levelname)s:%(name)s:%(funcNa...
Set python logging library config. Run this ONCE at the start of your process. It formats the python logging module's output. Defaults logging level to INFO = 20)
python
def set_root_logger(root_log_level, log_path=None): """Set the root logger 'pypyr'. Do this before you do anything else. Run once and only once at initialization. """ handlers = [] console_handler = logging.StreamHandler() handlers.append(console_handler) if log_path: file_handler ...
Set the root logger 'pypyr'. Do this before you do anything else. Run once and only once at initialization.
python
def get_parsed_context(pipeline, context_in_string): """Execute get_parsed_context handler if specified. Dynamically load the module specified by the context_parser key in pipeline dict and execute the get_parsed_context function on that module. Args: pipeline: dict. Pipeline object. c...
Execute get_parsed_context handler if specified. Dynamically load the module specified by the context_parser key in pipeline dict and execute the get_parsed_context function on that module. Args: pipeline: dict. Pipeline object. context_in_string: string. Argument string used to initialize...
python
def main( pipeline_name, pipeline_context_input, working_dir, log_level, log_path, ): """Entry point for pypyr pipeline runner. Call this once per pypyr run. Call me if you want to run a pypyr pipeline from your own code. This function does some one-off 1st time initialization befor...
Entry point for pypyr pipeline runner. Call this once per pypyr run. Call me if you want to run a pypyr pipeline from your own code. This function does some one-off 1st time initialization before running the actual pipeline. pipeline_name.yaml should be in the working_dir/pipelines/ directory. Ar...
python
def prepare_context(pipeline, context_in_string, context): """Prepare context for pipeline run. Args: pipeline: dict. Dictionary representing the pipeline. context_in_string: string. Argument string used to initialize context. context: pypyr.context.Context. Merge any new context genera...
Prepare context for pipeline run. Args: pipeline: dict. Dictionary representing the pipeline. context_in_string: string. Argument string used to initialize context. context: pypyr.context.Context. Merge any new context generated from context_in_string into this context inst...
python
def load_and_run_pipeline(pipeline_name, pipeline_context_input=None, working_dir=None, context=None, parse_input=True, loader=None): """Load and run the specified pypyr pipeline. T...
Load and run the specified pypyr pipeline. This function runs the actual pipeline by name. If you are running another pipeline from within a pipeline, call this, not main(). Do call main() instead for your 1st pipeline if there are pipelines calling pipelines. By default pypyr uses file loader. This m...
python
def run_pipeline(pipeline, context, pipeline_context_input=None, parse_input=True): """Run the specified pypyr pipeline. This function runs the actual pipeline. If you are running another pipeline from within a pipeline, call this, not main(). Do call main...
Run the specified pypyr pipeline. This function runs the actual pipeline. If you are running another pipeline from within a pipeline, call this, not main(). Do call main() instead for your 1st pipeline if there are pipelines calling pipelines. Pipeline and context should be already loaded. Args: ...
python
def run_step(context): """Write payload out to yaml file. Args: context: pypyr.context.Context. Mandatory. The following context keys expected: - fileWriteYaml - path. mandatory. path-like. Write output file to here. Will create...
Write payload out to yaml file. Args: context: pypyr.context.Context. Mandatory. The following context keys expected: - fileWriteYaml - path. mandatory. path-like. Write output file to here. Will create directories in path for you. ...
python
def run_step(context): """Print debug info to console. context is a dictionary or dictionary-like. If you use pypyr.steps.debug as a simple step (i.e you do NOT specify the debug input context), it will just dump the entire context to stdout. Configure the debug step with the following optional c...
Print debug info to console. context is a dictionary or dictionary-like. If you use pypyr.steps.debug as a simple step (i.e you do NOT specify the debug input context), it will just dump the entire context to stdout. Configure the debug step with the following optional context item: debug: ...
python
def get_error_name(error): """Return canonical error name as string. For builtin errors like ValueError or Exception, will return the bare name, like ValueError or Exception. For all other exceptions, will return modulename.errorname, such as arbpackage.mod.myerror Args: error: Except...
Return canonical error name as string. For builtin errors like ValueError or Exception, will return the bare name, like ValueError or Exception. For all other exceptions, will return modulename.errorname, such as arbpackage.mod.myerror Args: error: Exception object. Returns: ...
python
def get_module(module_abs_import): """Use importlib to get the module dynamically. Get instance of the module specified by the module_abs_import. This means that module_abs_import must be resolvable from this package. Args: module_abs_import: string. Absolute name of module to import. Rai...
Use importlib to get the module dynamically. Get instance of the module specified by the module_abs_import. This means that module_abs_import must be resolvable from this package. Args: module_abs_import: string. Absolute name of module to import. Raises: PyModuleNotFoundError: if mod...
python
def set_working_directory(working_directory): """Add working_directory to sys.paths. This allows dynamic loading of arbitrary python modules in cwd. Args: working_directory: string. path to add to sys.paths """ logger.debug("starting") logger.debug(f"adding {working_directory} to sys...
Add working_directory to sys.paths. This allows dynamic loading of arbitrary python modules in cwd. Args: working_directory: string. path to add to sys.paths
python
def assert_child_key_has_value(self, parent, child, caller): """Assert that context contains key that has child which has a value. Args: parent: parent key child: validate this sub-key of parent exists AND isn't None. caller: string. calling function name - this used...
Assert that context contains key that has child which has a value. Args: parent: parent key child: validate this sub-key of parent exists AND isn't None. caller: string. calling function name - this used to construct error messages Raises: ...
python
def assert_key_has_value(self, key, caller): """Assert that context contains key which also has a value. Args: key: validate this key exists in context AND has a value that isn't None. caller: string. calling function name - this used to construct ...
Assert that context contains key which also has a value. Args: key: validate this key exists in context AND has a value that isn't None. caller: string. calling function name - this used to construct error messages Raises: KeyNot...
python
def assert_keys_exist(self, caller, *keys): """Assert that context contains keys. Args: keys: validates that these keys exists in context caller: string. calling function or module name - this used to construct error messages Raises: KeyN...
Assert that context contains keys. Args: keys: validates that these keys exists in context caller: string. calling function or module name - this used to construct error messages Raises: KeyNotInContextError: When key doesn't exist in context.
python
def assert_keys_have_values(self, caller, *keys): """Check that keys list are all in context and all have values. Args: *keys: Will check each of these keys in context caller: string. Calling function name - just used for informational messages Raise...
Check that keys list are all in context and all have values. Args: *keys: Will check each of these keys in context caller: string. Calling function name - just used for informational messages Raises: KeyNotInContextError: Key doesn't exist ...
python
def get_formatted_iterable(self, obj, memo=None): """Recursively loop through obj, formatting as it goes. Interpolates strings from the context dictionary. This is not a full on deepcopy, and it's on purpose not a full on deepcopy. It will handle dict, list, set, tuple for iteration, w...
Recursively loop through obj, formatting as it goes. Interpolates strings from the context dictionary. This is not a full on deepcopy, and it's on purpose not a full on deepcopy. It will handle dict, list, set, tuple for iteration, without any especial cuteness for other types or types...
python
def get_formatted_string(self, input_string): """Return formatted value for input_string. get_formatted gets a context[key] value. get_formatted_string is for any arbitrary string that is not in the context. Only valid if input_string is a type string. Return a string i...
Return formatted value for input_string. get_formatted gets a context[key] value. get_formatted_string is for any arbitrary string that is not in the context. Only valid if input_string is a type string. Return a string interpolated from the context dictionary. If inpu...
python
def get_formatted_as_type(self, value, default=None, out_type=str): """Return formatted value for input value, returns as out_type. Caveat emptor: if out_type is bool and value a string, return will be True if str is 'True'. It will be False for all other cases. Args: ...
Return formatted value for input value, returns as out_type. Caveat emptor: if out_type is bool and value a string, return will be True if str is 'True'. It will be False for all other cases. Args: value: the value to format default: if value is None, set to thi...
python
def get_processed_string(self, input_string): """Run token substitution on input_string against context. You probably don't want to call this directly yourself - rather use get_formatted, get_formatted_iterable, or get_formatted_string because these contain more friendly error handling ...
Run token substitution on input_string against context. You probably don't want to call this directly yourself - rather use get_formatted, get_formatted_iterable, or get_formatted_string because these contain more friendly error handling plumbing and context logic. If you do want to ca...
python
def keys_of_type_exist(self, *keys): """Check if keys exist in context and if types are as expected. Args: *keys: *args for keys to check in context. Each arg is a tuple (str, type) Returns: Tuple of namedtuple ContextItemInfo, same order as *keys. ...
Check if keys exist in context and if types are as expected. Args: *keys: *args for keys to check in context. Each arg is a tuple (str, type) Returns: Tuple of namedtuple ContextItemInfo, same order as *keys. ContextItemInfo(key, ...
python
def merge(self, add_me): """Merge add_me into context and applies interpolation. Bottom-up merge where add_me merges into context. Applies string interpolation where the type is a string. Where a key exists in context already, add_me's value will overwrite what's in context alre...
Merge add_me into context and applies interpolation. Bottom-up merge where add_me merges into context. Applies string interpolation where the type is a string. Where a key exists in context already, add_me's value will overwrite what's in context already. Supports nested hierar...
python
def set_defaults(self, defaults): """Set defaults in context if keys do not exist already. Adds the input dict (defaults) into the context, only where keys in defaults do not already exist in context. Supports nested hierarchies. Example: Given a context like this: ...
Set defaults in context if keys do not exist already. Adds the input dict (defaults) into the context, only where keys in defaults do not already exist in context. Supports nested hierarchies. Example: Given a context like this: key1: value1 key2: ...
python
def run_step(self, rewriter): """Do the file in to out rewrite. Doesn't do anything more crazy than call files_in_to_out on the rewriter. Args: rewriter: pypyr.filesystem.FileRewriter instance. """ assert rewriter, ("FileRewriter instance required to run " ...
Do the file in to out rewrite. Doesn't do anything more crazy than call files_in_to_out on the rewriter. Args: rewriter: pypyr.filesystem.FileRewriter instance.
python
def run_step(self, representer): """Do the object in-out rewrite. Args: representer: A pypyr.filesystem.ObjectRepresenter instance. """ assert representer, ("ObjectRepresenter instance required to run " "ObjectRewriterStep.") rewriter = ...
Do the object in-out rewrite. Args: representer: A pypyr.filesystem.ObjectRepresenter instance.
python
def run_step(self): """Do the file in-out rewrite.""" rewriter = StreamRewriter(self.context.iter_formatted_strings) super().run_step(rewriter)
Do the file in-out rewrite.
python
def run_step(self): """Write in to out, replacing strings per the replace_pairs.""" formatted_replacements = self.context.get_formatted_iterable( self.replace_pairs) iter = StreamReplacePairsRewriterStep.iter_replace_strings( formatted_replacements) rewriter = St...
Write in to out, replacing strings per the replace_pairs.
python
def iter_replace_strings(replacements): """Create a function that uses replacement pairs to process a string. The returned function takes an iterator and yields on each processed line. Args: replacements: Dict containing 'find_string': 'replace_string' pairs Return...
Create a function that uses replacement pairs to process a string. The returned function takes an iterator and yields on each processed line. Args: replacements: Dict containing 'find_string': 'replace_string' pairs Returns: function with signature: iterator of...
python
def run_step(context): """Set new context keys from formatting expressions with substitutions. Context is a dictionary or dictionary-like. context['contextSetf'] must exist. It's a dictionary. Will iterate context['contextSetf'] and save the values as new keys to the context. For example, say ...
Set new context keys from formatting expressions with substitutions. Context is a dictionary or dictionary-like. context['contextSetf'] must exist. It's a dictionary. Will iterate context['contextSetf'] and save the values as new keys to the context. For example, say input context is: key1...
python
def cast_to_type(obj, out_type): """Cast obj to out_type if it's not out_type already. If the obj happens to be out_type already, it just returns obj as is. Args: obj: input object out_type: type. Returns: obj cast to out_type. Usual python conversion / casting rules apply. ...
Cast obj to out_type if it's not out_type already. If the obj happens to be out_type already, it just returns obj as is. Args: obj: input object out_type: type. Returns: obj cast to out_type. Usual python conversion / casting rules apply.
python
def get_pipeline_yaml(file): """Return pipeline yaml from open file object. Use specific custom representers to model the custom pypyr pipeline yaml format, to load in special literal types like py and sic strings. If looking to extend the pypyr pipeline syntax with special types, add these to the...
Return pipeline yaml from open file object. Use specific custom representers to model the custom pypyr pipeline yaml format, to load in special literal types like py and sic strings. If looking to extend the pypyr pipeline syntax with special types, add these to the tag_representers list. Args: ...
python
def get_yaml_parser_roundtrip(): """Create the yaml parser object with this factory method. The round-trip parser preserves: - comments - block style and key ordering are kept, so you can diff the round-tripped source - flow style sequences ( ‘a: b, c, d’) (based on request and test by ...
Create the yaml parser object with this factory method. The round-trip parser preserves: - comments - block style and key ordering are kept, so you can diff the round-tripped source - flow style sequences ( ‘a: b, c, d’) (based on request and test by Anthony Sottile) - anchor names that...
python
def get_yaml_parser_roundtrip_for_context(): """Create a yaml parser that can serialize the pypyr Context. Create yaml parser with get_yaml_parser_roundtrip, adding Context. This allows the yaml parser to serialize the pypyr Context. """ yaml_writer = get_yaml_parser_roundtrip() # Context is a...
Create a yaml parser that can serialize the pypyr Context. Create yaml parser with get_yaml_parser_roundtrip, adding Context. This allows the yaml parser to serialize the pypyr Context.
python
def run_step(context): """Load a json file into the pypyr context. json parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, retur...
Load a json file into the pypyr context. json parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, returned context['eggs'] will be 'b...
python
def _ignore_request(self, path): """Check to see if we should ignore the request.""" return any([ re.match(pattern, path) for pattern in QC_SETTINGS['IGNORE_REQUEST_PATTERNS'] ])
Check to see if we should ignore the request.
python
def _ignore_sql(self, query): """Check to see if we should ignore the sql query.""" return any([ re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS'] ])
Check to see if we should ignore the sql query.
python
def _duplicate_queries(self, output): """Appends the most common duplicate queries to the given output.""" if QC_SETTINGS['DISPLAY_DUPLICATES']: for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']): lines = ['\nRepeated {0} times.'.format(count)] ...
Appends the most common duplicate queries to the given output.
python
def _calculate_num_queries(self): """ Calculate the total number of request and response queries. Used for count header and count table. """ request_totals = self._totals("request") response_totals = self._totals("response") return request_totals[2] + response_to...
Calculate the total number of request and response queries. Used for count header and count table.
python
def _process_settings(**kwargs): """ Apply user supplied settings. """ # If we are in this method due to a signal, only reload for our settings setting_name = kwargs.get('setting', None) if setting_name is not None and setting_name != 'QUERYCOUNT': return # Support the old-style s...
Apply user supplied settings.
python
def _get_webapi_requests(self): """Update headers of webapi for Requests.""" headers = { 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': ...
Update headers of webapi for Requests.
python
def _build_response(self, resp): """Build internal Response object from given response.""" # rememberLogin # if self.method is 'LOGIN' and resp.json().get('code') == 200: # cookiesJar.save_cookies(resp, NCloudBot.username) self.response.content = resp.content self.res...
Build internal Response object from given response.
python
def send(self): """Sens the request.""" success = False if self.method is None: raise ParamsError() try: if self.method == 'SEARCH': req = self._get_requests() _url = self.__NETEAST_HOST + self._METHODS[self.method] ...
Sens the request.
python
def set_option(name, value): """ Set plydata option Parameters ---------- name : str Name of the option value : object New value of the option Returns ------- old : object Old value of the option See also -------- :class:`options` """ ol...
Set plydata option Parameters ---------- name : str Name of the option value : object New value of the option Returns ------- old : object Old value of the option See also -------- :class:`options`
python
def group_indices(self): """ Return group indices """ # No groups if not self.plydata_groups: return np.ones(len(self), dtype=int) grouper = self.groupby() indices = np.empty(len(self), dtype=int) for i, (_, idx) in enumerate(sorted(grouper.in...
Return group indices
python
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This is the function called after expressions created and adde...
python
def _get_base_dataframe(df): """ Remove all columns other than those grouped on """ if isinstance(df, GroupedDataFrame): base_df = GroupedDataFrame( df.loc[:, df.plydata_groups], df.plydata_groups, copy=True) else: base_df = pd.DataFrame(index=df.index) re...
Remove all columns other than those grouped on
python
def _add_group_columns(data, gdf): """ Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x...
Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x': range(3)}, groups=['g']) >>> _add_group_...
python
def _create_column(data, col, value): """ Create column in dataframe Helper method meant to deal with problematic column values. e.g When the series index does not match that of the data. Parameters ---------- data : pandas.DataFrame dataframe in which to insert value col :...
Create column in dataframe Helper method meant to deal with problematic column values. e.g When the series index does not match that of the data. Parameters ---------- data : pandas.DataFrame dataframe in which to insert value col : column label Column name value : obje...
python
def build_expressions(verb): """ Build expressions for helper verbs Parameters ---------- verb : verb A verb with a *functions* attribute. Returns ------- out : tuple (List of Expressions, New columns). The expressions and the new columns in which the results of...
Build expressions for helper verbs Parameters ---------- verb : verb A verb with a *functions* attribute. Returns ------- out : tuple (List of Expressions, New columns). The expressions and the new columns in which the results of those expressions will be stored...
python
def process(self): """ Run the expressions Returns ------- out : pandas.DataFrame Resulting data """ # Short cut if self._all_expressions_evaluated(): if self.drop: # Drop extra columns. They do not correspond to ...
Run the expressions Returns ------- out : pandas.DataFrame Resulting data
python
def _all_expressions_evaluated(self): """ Return True all expressions match with the columns Saves some processor cycles """ def present(expr): return expr.stmt == expr.column and expr.column in self.data return all(present(expr) for expr in self.expressions)
Return True all expressions match with the columns Saves some processor cycles
python
def _get_group_dataframes(self): """ Get group dataframes Returns ------- out : tuple or generator Group dataframes """ if isinstance(self.data, GroupedDataFrame): grouper = self.data.groupby() # groupby on categorical columns ...
Get group dataframes Returns ------- out : tuple or generator Group dataframes
python
def _evaluate_group_dataframe(self, gdf): """ Evaluate a single group dataframe Parameters ---------- gdf : pandas.DataFrame Input group dataframe Returns ------- out : pandas.DataFrame Result data """ gdf._is_copy...
Evaluate a single group dataframe Parameters ---------- gdf : pandas.DataFrame Input group dataframe Returns ------- out : pandas.DataFrame Result data
python
def _concat(self, egdfs): """ Concatenate evaluated group dataframes Parameters ---------- egdfs : iterable Evaluated dataframes Returns ------- edata : pandas.DataFrame Evaluated data """ egdfs = list(egdfs) ...
Concatenate evaluated group dataframes Parameters ---------- egdfs : iterable Evaluated dataframes Returns ------- edata : pandas.DataFrame Evaluated data
python
def _resolve_slices(data_columns, names): """ Convert any slices into column names Parameters ---------- data_columns : pandas.Index Dataframe columns names : tuple Names (including slices) of columns in the dataframe. Returns...
Convert any slices into column names Parameters ---------- data_columns : pandas.Index Dataframe columns names : tuple Names (including slices) of columns in the dataframe. Returns ------- out : tuple Names of colu...
python
def select(cls, verb): """ Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains ...
Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains - matches
python
def _at(cls, verb): """ A verb with a select text match """ # Named (listed) columns are always included columns = cls.select(verb) final_columns_set = set(cls.select(verb)) groups_set = set(_get_groups(verb)) final_columns_set -= groups_set - set(verb.nam...
A verb with a select text match
python
def _if(cls, verb): """ A verb with a predicate function """ pred = verb.predicate data = verb.data groups = set(_get_groups(verb)) # force predicate if isinstance(pred, str): if not pred.endswith('_dtype'): pred = '{}_dtype'.f...
A verb with a predicate function
python
def get_verb_function(data, verb): """ Return function that implements the verb for given data type """ try: module = type_lookup[type(data)] except KeyError: # Some guess work for subclasses for type_, mod in type_lookup.items(): if isinstance(data, type_): ...
Return function that implements the verb for given data type
python
def Expression(*args, **kwargs): """ Return an appropriate Expression given the arguments Parameters ---------- args : tuple Positional arguments passed to the Expression class kwargs : dict Keyword arguments passed to the Expression class """ # dispatch if not hasat...
Return an appropriate Expression given the arguments Parameters ---------- args : tuple Positional arguments passed to the Expression class kwargs : dict Keyword arguments passed to the Expression class
python
def with_outer_namespace(self, outer_namespace): """Return a new EvalEnvironment with an extra namespace added. This namespace will be used only for variables that are not found in any existing namespace, i.e., it is "outside" them all.""" return self.__class__(self._namespaces + [outer_...
Return a new EvalEnvironment with an extra namespace added. This namespace will be used only for variables that are not found in any existing namespace, i.e., it is "outside" them all.
python
def subset(self, names): """Creates a new, flat EvalEnvironment that contains only the variables specified.""" vld = VarLookupDict(self._namespaces) new_ns = dict((name, vld[name]) for name in names) return EvalEnvironment([new_ns], self.flags)
Creates a new, flat EvalEnvironment that contains only the variables specified.
python
def Q(name): """ Quote a variable name A way to 'quote' variable names, especially ones that do not otherwise meet Python's variable name rules. Parameters ---------- name : str Name of variable Returns ------- value : object Value of variable Examples ...
Quote a variable name A way to 'quote' variable names, especially ones that do not otherwise meet Python's variable name rules. Parameters ---------- name : str Name of variable Returns ------- value : object Value of variable Examples -------- >>> import ...
python
def regular_index(*dfs): """ Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets th...
Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets the unordered indices of any datafr...
python
def unique(lst): """ Return unique elements :class:`pandas.unique` and :class:`numpy.unique` cast mixed type lists to the same type. They are faster, but some times we want to maintain the type. Parameters ---------- lst : list-like List of items Returns ------- ou...
Return unique elements :class:`pandas.unique` and :class:`numpy.unique` cast mixed type lists to the same type. They are faster, but some times we want to maintain the type. Parameters ---------- lst : list-like List of items Returns ------- out : list Unique items...
python