Util
mongorunway.util
¤
Utilities.
The module contains utilities that can be used in a project.
Info
This module is independent of all other modules and can only use built-in or third-party libraries.
__all__: typing.Sequence[str] = ('get_module', 'as_snake_case', 'import_obj', 'convert_string', 'build_mapping_values', 'build_optional_kwargs', 'is_valid_filename', 'hexlify')
module-attribute
¤
number_pattern: typing.Final[typing.Pattern[str]] = re.compile('\n [-+]? # Matches an optional sign character (- or +)\n (?: # Non-capturing group:\n \\d{1,3} # Matches 1 to 3 digits\n (?:_\\d{3})* # Matches an underscore (_) followed by exactly 3 digits, \n # repeated zero or more times.\n | # Alternation operator, allows matching either the previous pattern \n # or the following pattern.\n [\\d_]+ # Matches one or more digits or underscores\n (?:\\.\\d+)? # Matches an optional decimal part, where \\.\\d+ matches a dot \n # followed by one or more digits.\n )\n ', flags=re.VERBOSE)
module-attribute
¤
Regular expression for numeric values.
The number_pattern constant is a regular expression pattern used for matching numeric values.
string_case_pattern: typing.Final[typing.Pattern[str]] = re.compile('\n (?<=_) # Positive lookbehind assertion for an underscore character\n (\\w+) # Match and capture one or more word characters (alphanumeric or underscore)\n | # Or\n ([A-Z][a-z]+) # Match and capture an uppercase letter followed by one or more lowercase letters\n | # Or\n ([a-z]+) # Match and capture one or more lowercase letters\n (?=[A-Z]) # Positive lookahead assertion for an uppercase letter\n ', flags=re.VERBOSE)
module-attribute
¤
Regular expression for string cases.
The string_case_pattern
constant is a regular expression pattern
used for matching different cases in strings.
SystemTimer
¤
Implementation of a system timer for code benchmarks.
This class represents an implementation of a system timer for measuring
the execution time of a specific code block. It is a context manager and
can be conveniently used with the with
statement.
Source code in mongorunway\util.py
__slots__: typing.Sequence[str] = ('_start', '_executed_in')
instance-attribute
class-attribute
¤
executed_in: float
property
¤
Returns the execution time of a code block.
Returns the time it took for the code block to execute. The
calculation is done using the system time from the time
module.
RETURNS | DESCRIPTION |
---|---|
float
|
The execution time of the code block. |
start: float
property
¤
Returns the start time of the benchmark.
Returns the system time that was set in the __enter__
method of
this class.
RETURNS | DESCRIPTION |
---|---|
float
|
The system time when the code block started execution. |
__enter__()
¤
__exit__(exc_type, exc_val, exc_tb)
¤
as_snake_case(obj)
¤
Converts an object to snake case format.
Converts an object to snake case format regardless of the type of the
object passed. If the object is an instance of the str
class, the object
itself will be converted. Otherwise, the obj.__name__
will be taken,
and if it is not available, the attribute will be taken from the type of
the object passed.
PARAMETER | DESCRIPTION |
---|---|
obj |
The object, name, or value to be converted to snake case. |
RETURNS | DESCRIPTION |
---|---|
str
|
The converted name of the object or its value in snake case. It may return the original object if the object does not match the regular expression. |
Example¤
>>> class DummyClass: pass
>>> dummy_obj = DummyClass()
>>> as_snake_case(DummyClass)
'dummy_class'
>>> as_snake_case(dummy_obj) # Takes `type(dummy_obj).__name__` .
'dummy_class'
>>> as_snake_case("snake_case_str")
'snake_case_str'
>>> as_snake_case("camelCase")
'camel_case'
Source code in mongorunway\util.py
build_mapping_values(mapping)
¤
Converts string values in a mutable mapping.
Converts string values in a mutable mapping to corresponding named objects. If a string fails validation, the original value is retained.
PARAMETER | DESCRIPTION |
---|---|
mapping |
Mutable mapping whose values need to be converted.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
typing.MutableMapping[_T, typing.Any]
|
Mutable mapping with converted values. |
Example¤
See Also¤
convert_string
Source code in mongorunway\util.py
build_optional_kwargs(keys, mapping)
¤
Converts string values in a mutable mapping.
Converts string values in a mutable mapping to corresponding named objects. If the value of a dictionary is None, the loop will move to the next iteration. Returns a mutable mapping with the keys passed to this function.
PARAMETER | DESCRIPTION |
---|---|
keys |
Keys of optional values to be converted if their value is not None. |
mapping |
Mutable mapping whose values need to be converted. |
RETURNS | DESCRIPTION |
---|---|
typing.MutableMapping[_T, typing.Any]
|
Mutable mapping with all non-None values converted. |
Example¤
See Also¤
convert_string
Source code in mongorunway\util.py
convert_string(value)
¤
Converts a string.
Converts a string depending on the received value. Case-insensitive string conversion. If the string fails all the checks, the passed value will be returned.
PARAMETER | DESCRIPTION |
---|---|
value |
The value that needs to be converted.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
typing.Union[int, float, bool, str, None]
|
None, if the value is one of {"none", "nothing", "undefined"}. |
See Also¤
number_pattern : Relationship. distutils.util.strtobool : Relationship.
Source code in mongorunway\util.py
get_module(directory, filename)
¤
Loads a module from given directory.
Load and return a module based on the given directory and filename. Also supports the format without a file extension e.g. '.py' .
PARAMETER | DESCRIPTION |
---|---|
directory |
The path to the directory where the file is located.
TYPE:
|
filename |
The name of the file containing the module.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
types.ModuleType
|
The module object that is loaded from the file. |
RAISES | DESCRIPTION |
---|---|
ModuleNotFoundError
|
If the file specified by |
Example¤
>>> from types import ModuleType
... # Obtains the current file util.py when running doctest
... # in the current directory.
>>> assert isinstance(get_module("", "util.py"), ModuleType)
...
>>> from types import ModuleType
... # Also supports the format without a file extension.
>>> assert isinstance(get_module("", "util"), ModuleType)
See Also¤
importlib.spec_from_file_location
Source code in mongorunway\util.py
hexlify(binary)
¤
Converts a binary object to hexadecimal.
Converts a binary object to a more user-friendly hexadecimal string. This method can be useful for converting session IDs in both pymongo and mongorunway, as these tools use the same format for identifiers.
PARAMETER | DESCRIPTION |
---|---|
binary |
Binary representation of the object to be converted to a hexadecimal string.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
The converted binary object as a hexadecimal string. |
Source code in mongorunway\util.py
import_obj(obj_path, /, cast)
¤
Imports a class from the specified module.
Imports a class from the specified module. The module path should be specified using dot notation, with the class itself at the end.
PARAMETER | DESCRIPTION |
---|---|
obj_path |
The path to the obj to be imported.
TYPE:
|
cast |
The type to which the value should be cast. This is used to provide more clarity in the code. This parameter is also useful for compatibility with type checkers.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
_TT
|
The type to which we cast the imported obj. |
See Also¤
importlib.import_module
Source code in mongorunway\util.py
is_valid_filename(directory, filename)
¤
Validates the file in the given directory.
Check whether a given filename is a valid migration file in the given directory.
PARAMETER | DESCRIPTION |
---|---|
directory |
The path of the directory where the file is located.
TYPE:
|
filename |
The name of the file to be checked.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool
|
True if the filename is a valid migration file, False otherwise. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the value passed to the directory parameter is not a directory. |
Notes¤
The function checks if a file exists in the specified directory. Additionally, the file must have the extension '.py' and should not start with a dunder1.
References¤
-
Dunder: The term "dunder" is a short form of "double underscore" and is commonly used to refer to special methods or attributes in Python that are surrounded by double underscores on both sides, such as init or name. ↩
Source code in mongorunway\util.py
timeit_func(func, *args, **kwargs)
¤
Benchmarks the execution time of a function.
Returns the execution time of a function and the resulting output of calling the function with given parameters.
PARAMETER | DESCRIPTION |
---|---|
func |
The function whose execution time needs to be benched.
TYPE:
|
args |
Positional arguments of a function.
TYPE:
|
kwargs |
Keyword arguments of a function
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tuple[_T, float]
|
A tuple where the first element is the type of the returned result of the function, and the second element is the time taken to execute the function. |
See Also¤
SystemTimer