The main package and a background support of project PyCAMIA.
Project description
pycamia
[TOC]
Introduction
pycamia is the base package affiliated to project PyCAMIA. It is a collection of different useful tools necessary in Python programming. pycamia was designed for Python v3.6+. The most important functions (and most frequently used) of this package include:
- [
@alias](#packagedecorators) decorator to create alias names for an object. - [
get_environ_vars()](#packageenvironment) to get the variables from the parent scope of the current function. - [
avouch(bool, assertion_text_or_raised_error)](#packageexception) to avouch (i.e. assert) with a self-designed error message (or the input expression by default). - [
touch(expression_or_function, *args, default=None, ...)](#packageexception) to touch a dangerous function (or a string of code), return the value if no error has occurred but a default value if errors are raised. - [
print=Sprint()](#packageinout) to "print" to a string, instead of the console. - [
with logging(path)](#packagelogging) to save to log files by simply using'print'. - [
collector = Collector()](#packageloopop) to collect metrics in each iteration as numpy arrays. - [
with TaskProgress() as iterate](#packageloopop) to create progress bar for each line of outputs. - More to come...
In detail, the package consists of the following sub-packages.
decoratorsis the package containing the decorators: e.g. use @aliasto call a function with multiple names; use@restore_type_wrapperto cast the return value as the first input argument.environmentis the package containing functions to inspect the context: e.g. useget_environ_vars()in a function to get the variables in the scope calling the function.exceptionis the package to handle exceptions: e.g. usetouch("a[i]")to try a function (or code in str) and suppress the error; useavouch(assertion, "error message")to assert with comments; useError("DIY")to create an Error.functionsis the package of special (and commonly trivial) functions: e.g. useempty_functionfor an empty function.inoutis the package to extend the input/output: e.g. usesprint=SPrint()to print into a string; usewith no_print:to suppress the console output.listopis the collection of advanced functions for lists: e.g. useprodto find the product of a list; useflatten_listto flatten a nested list.loggingis the package for logs: e.g. usewith logging(file_path):to log all the printed contents (usingprint) to the log file; usestart_logging(file_path)to serve this purpose for the rest of the program.loopopis the package giving support to loops: e.g. useCollectorto register the output of each iteration and retrieve the time sequence at the end of the loop; useTaskProgress(oriterate) to create a progress bar for the output.- manager is the package to manage file and package info: e.g. use
with __info__:to check the dependencies and have better error message; useinfo_managerto organize the file information; useVersionto parse the version strings and compare. stropis the collection of advanced functions for strings: e.g. usetokenizeto tokenize a string by splitting at places not nested with brackets; usefind_allto find all indices for matched sub-strings.structuresis the collection of extended data structures for python: e.g. usestruct(a=1, b=2)to create a structure that has the properties'a'and'b'.systemis the package that communicates with the operating system: usePath.curpath/"folder"/"filename.xx"to create the path object which can be used as a string but is easy to modify; usecopyto copy a file from a destination to another.- timing is the package to time the executions: e.g. use
with scope(scope_name):to record time spent for a set of commands. mathis not officially open access so far. It is the package of mathematic objects.moreis a collection of uncategorized functions, one needs to import them directly frompycamia.more.numpyopis the package for numpy operations, which currently consists of functions changing dtype into signed/unsigned formats, this package is currently deprecated.
Installation
This package can be installed by pip install pycamia or moving the source code to the directory of python libraries (the source code can be downloaded on github or PyPI).
pip install pycamia
Usage
package decorators
This package contains the useful decorators which is expected to extend in the future.
-
Use
@aliasto create alias names, e.g.... @other_wrappers # wrappers for function `func_b` only. ... @alias("func_a", b=1) # wrappers in between are for functions `func_a` and `func_b`. ... @alias("func_c", b=2) ... @some_wrappers # wrappers for functions `func_a`, `func_b` and `func_c`. ... def func_b(x, b): ... print(x+b) ... >>> func_a(1), func_b(2, 4), func_c(7) (2, 6, 9)
or one can also use it for non-function objects,
>>> a = alias('b')(10) >>> a, b (10, 10) >>> @alias("B", "C") ... class A: ... @alias('a') ... @property ... def name(self): return 1 ... >>> B().a, A().name (1, 1)
Note that the
@aliaswon't change the'__name__'property. -
Use
@restore_type_wrapperto cast the return value back to the first input argument.
package environment
This package fetches the surrounding environment of the call. i.e.
a.py:
from b import a_func
def some_func(*args):
here_is_the_var_needed = []
a_func()
print(here_is_the_var_needed)
b.py:
from pycamia import get_environ_vars
def a_func():
vars = get_environ_vars().locals
cell_var = vars['here_is_the_var_needed']
cell_var.append(sth)
vars['here_is_the_var_needed'] = cell_var
-
Use
v = get_environ_vars()to get anEnvironVarsobject which can provide access to the variables in the surrounding environment by dictionary operations. -
Use
v = get_environ_vars().localsandv = get_environ_locals()(orv = get_environ_vars().globalsandv = get_environ_globals()for global variables) to get the dictionary of local or global variables in the parent environment. If the result is out of expectations, please contact the developer. -
Use
update_locals_by_environ()in a scope to copy the environmental variables to the local scope. One can then directly use the variables. However, please note that this operation may cause overriding of previously defined scope variables (including function arguments). -
Use
get_declaration(functional)to get the declaration line offunctional. One is encouraged to useget_virtual_declarationin packagepyoverload(a package installed bypip install pyoverload, which is in the same project) to get the declaration reorganized by function properties (this would be faster as it reads from memory). -
Use
get_args_expression()in a function to get the input arguments when this function is called. Note that this can obtain the expression of the input argument instead of only the variable name and the value, as follows,>>> def func(x): ... print(get_args_expression()) ... >>> func(x for x in range(100) if x % 2 == 1) x for x in range(100) if x % 2 == 1
package exception
This package handles exceptions with touch and an alias avouch for assert.
-
Use
touch(function_or_str)to try a function and suppress the error in the meantime. e.g.touch(lambda: 1/a)returnsNoneto tell you that an exception occurs whena=0, but returns1whena=1.One can use
default=...to identify the value return when an error occurs anderror_type=TypeErrorto only catch theTypeErrors. What's more, one can use a string of expressions as the touch subject, or a function with input arguments directly sent to touch. -
Use
crashed(function) -> boolto check whether a function has failed or not. -
Use
avouch(bool_to_be_tested, assertion_text_or_error)to avouch that the given expression is true and output your designedassertion_textwhen the test fails. e.g.untitled.py: from pycamia import avouch avouch(isinstance(1, str)) Traceback (most recent call last): [...omitted...] AssertionError: Failure in assertion 'isinstance(1, str)' >>> from pycamia import avouch >>> avouch(isinstance(1, str), TypeError("1 is not a string")) Traceback (most recent call last): [...omitted...] TypeError: 1 is not a string
Note that the auto-generated assertion message may be
'<unreachable arg expression>'in the Python console due to the file-reading logic ofget_arg_expression, please contact the developer if you have a better idea of getting the expression and are willing to share. -
Use
Error("name")to create a new error type. It is equivalent to creating an Error tag byclass {name}Error(Exception): pass.
package functions
This package contains simple functions which is the simplest package in the project so far.
- Use
empty_functionfor a function that does nothing and returnsNone. One can put any argument to the function but nothing would happen. - Use
const_function(a)for a function that accepts any argument but does nothing and always returnsa. - Use
identity_function(*x)for a function that returns exactly the input (though multiple inputs will be returned as a tuple).
package inout
This package manipulates the input/output. Currently, it only deals with print. Shell handler or other in & out functions will be added here in the future.
-
Use
"with no_out:"to suppress the console output. Although not recommended, one can usewith no_out as out_stream:andoutput = str(out_stream)inside the'with'scope to fetch the current accumulated output. -
Use
"with no_print:"to suppress the console output, including the error information instd_err. -
Use
sprint = SPrint()to create a functionsprintthat collects the printed text.from pycamia import SPrint sprint = SPrint() output_from_middle = sprint(output_str, and_other_variables) # Just like 'print' sprint(something_else) output = sprint.text
-
Use
StrIO()to create a stream
package logging
This package deals with loggings.
-
Use
"with logging(log_file_path):"to create a log file of namelog_file_pathand record all the the outputs using functionprintinside the scope to this log file.loggingtakes the following keyword arguments:-
log_dir: the directory for the logging file, it is set when file path is not provided. The default file name would be{python_file_name}.log. -
prefix: the prefix for each line in the logging file,"{time}"by default indicating the time of print.timeis the only supported tag currently, please contact the developer if you have suggestions of more useful tags. -
exc_remove: whether to remove the logging file when an exception occurs. Please note that one doesn't have to worry about the lost of exception as they will be kept in an additional fileerror_msgs.log. This argument is set toTrueby default to avoid useless log files using debugging.P.S. Manually terminating the python process by
'KeyboardInterrupt'will not cause the removal of the log file (the log file will be marked as'interrupted'instead) so that the outputs are kept for reference although the exception will be recorded inerror_msgs.log. One needs to manually delete the log file if it is not needed. -
line_width: the number of characters in a single line which is $100$ by default. -
_vars: private argument for environmental variables, one can use_var=globals()if a'problem in stacks'is raised.
-
-
Use
start_logging(log_file_path)to start the logging for the rest of the program.
package loopop
This package helps users to manage loops in python.
-
Use
collector = Collector(max_storage)to create a metric collector. In each loop, one can 'collect' the output in the iteration and get them back as an array. Keyword argumentmax_storagedetermines how many values should be stored in the array. Not limit is set by default.In each loop, use
collector.register(name, value, format)to collect the value with the format follows the python formatting protocol. If the format string contains two formats seperated by a slash:".4f/.3f", the first format will be used for mean value and the second for the standard deviation (in methodsas_str_tuple,as_pmandas_latex.Use negetive sign to eliminate the
0before the decimal point, i.e. format".4f"will make $0.23215$ the string"0.2322"but"-.4f"will result in".2322".One can also place the format right after a colon in name, i.e.
register("metric:.4f", 0.23215). -
Use
TaskProgress()(or its instance aliasiterate) to create a progress bar before the output lines.from pycamia import iterate, TaskProgress # Usage #1 with iterate: for i in iterate(100): ... print([...something...]) # Usage #2 with TaskProgress(progress_len=10, n_timespan_store=20, show_progress_bar=True, breakable=True, break_key=None) as iterate: for i in iterate([2,3,4,...]): ... print([...something...]) # Usage #3 for i in iterate(100): for j in iterate(1000): ... print(iterate.prefix, [...something...])
The keyword arguments determine the length (number of characters) of the progress bar (
progress_len), the recorded iteration time for remaining time estimation (n_timespan_store), whether to show progress bar (show_progress_bar), whether the loops can be terminated by hot keys (breakable) and the hot key for breaking the loops (break_key).The hot key is in format like
'ctrl+d'. Use'+'to connect the keys and lower-cased words for control keys.iterate(*)for each loop takes an integer of a list (or iterable with length) as the input. It can also accept the previous keyword arguments (exceptprogress_len), except they will only take effect in the sole loop (neither the outer loops nor the inner ones).
package listop
This package cope with list objects, containing useful functions for lists.
- Use
argmin(list, domain)to find the indices for the minimal value in list. The function only search in the indicesdomain. A list is output as there may be multiple entries. - Use
argmaxto find the indices for the maximal value, similar toargmin. - Use
flatten_listto unwrap the list elements to create a list with no element in typelist. - Use
prodto obtain the product of all numbers in the list. - Use
itemto fetch the only element in the list. An error will be raised if there isn't any or are more than 1 elements.
package manager
This package manages the info of packages and files. One can use it to organize the project.
- Use
__info__ = info_manager(project="PyCAMIA", ...)to list the properties at the front of files. This serve as a brief introduction to readers. - Use
info_managerat the beginning of__init__.py,pack.pyuses it to create the portrait of a package. - Use
__info__.check_requires()to automatically check if the dependencies in attributerequiresexist or not. This is commonly used in__init__.py. One can use__info__ = info_manager(...).check()to perform an in-place check. - Use
with __info__:before importing required dependencies as well to perform a double check.
package strop
This package copes with str objects.
- Use
str_lento find the ASCII length for a string, with a length2for wide characters. - Use
str_sliceto slice a string by given indices. - Use
find_allto obtain all the indices of a given string.str_slice(s, find_all(s, k))is equivalent tos.split(k). - Use
sorted_dict_reprto create a repr string for a dictionary with ordered key. - Use
enclosed_objectto find the first object enclosed by brackets. - Use
tokenizeto split a string without breaking enclosed objects. This is useful in breaking text of dictionary structures or arguments. e.g. one can usetokenize(args, sep=[',', '='])[::2]to find the argument names ifargsis a string in the formatkey1=value1, key2 = value2, ....
package structures
package system
package timing
This package use the time spent of commands to perform useful inspection or organization of the codes.
- Use
@time_thisto time a function. - Use
with Timer("name"):to time a series of commands. - Use
with scope("name"):to nest a series of commands. It is an alias ofTimer. - Use
with scope("name"), jump:to jump a series of commands. - Use
with scope("name"), Jump(False):to disable the jump. - Use
wf = Workflow("step1", "step2")andwith wf("step1(2)"), wf.use_tag:before commands of "step1(2)" to create a workflow. One can change the arguments in the init function to decide which steps to run. - Use
@periodic(seconds, max_repeat)to run a function repeatedly.
package math
package more
Currently, only once is contained in the more package.
Adding it in a function to check if the function is run once or not.
package numpyop
Waiting to Be Improved
- More functions will be added in the future, including path handler, tools for shell and so on.
- Contact us to make suggestions.
Acknowledgment
@Yuncheng Zhou: Developer
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pycamia-1.0.41.tar.gz.
File metadata
- Download URL: pycamia-1.0.41.tar.gz
- Upload date:
- Size: 431.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b51d6e409d824048fa5d6d7ec5ae52eefc0af597ca448e8d310c9a6fa377c762
|
|
| MD5 |
1e450ffe0da89aa0d1e299537bcfc0c0
|
|
| BLAKE2b-256 |
90ee1fefeb70714f9fafdd64723653f02dd3a5a880311473d3b3a4c4dc3eb175
|
File details
Details for the file pycamia-1.0.41-py3-none-any.whl.
File metadata
- Download URL: pycamia-1.0.41-py3-none-any.whl
- Upload date:
- Size: 450.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d4814e7c6aeedcfdcb72e5201de6cede1a3d1366e929601c994aa028e2bac36f
|
|
| MD5 |
c1e3e68f3671bc213bb7cde851f0ca23
|
|
| BLAKE2b-256 |
995a024c085d52a4ab058d25b505ad798ecd28eeaf8f13e2f4a924c2a61d710f
|