jmbuilder.utils package#

Utilities Module for JMBuilder

This module provide utilities for JMBuilder package.

Copyright (c) 2023-2024 Ryuu Mitsuki.

class jmbuilder.utils.JMProperties(filename: Union[str, TextIO], *, encoding: str = 'UTF-8')[source]#

Bases: UserDict

This class provides a convenient way to parse properties files and access their contents.

Parameters:
filenamestr or TextIO

The filename or file object to read properties from. If a filename is provided, it checks for the file’s existence, opens the file stream, and retrieves the properties. If a file object is provided, it directly reads the properties from it.

encodingstr, optional

The encoding to use when opening the file stream. If not specified, it uses the encoding from locale.getpreferredencoding(). Defaults to system’s preferred encoding.

Raises:
JMParserError

If an error occurs while reading and parsing the properties file.

FileNotFoundError

If the specified file path does not exist.

ValueError

If the filename parameter is None.

Attributes:
dataDict[str, str]

A dictionary containing all the parsed properties.

filenamestr

An absolute path to the specified property file.

Methods

clear()

get(k[,d])

items()

keys()

pop(k[,d])

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[,d])

update([E, ]**F)

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()

copy

fromkeys

_abc_impl = <_abc_data object>#
jmbuilder.utils.init_logger(filename: Optional[str] = None, *, fmt: Optional[Union[str, Formatter]] = None, level: int = 10) Logger[source]#

Initializes and creates a new Logger object.

Parameters:
filenamestr or None, optional

A string representing the name of the logger file. If specified, logs will be written to the specified file, otherwise logs will be printed to stderr (standard error). Default is None.

fmtstr or logging.Formatter, optional

A string representation of the log formatter or an object of logging.Formatter class. If not specified, a customized formatter will be used. See CUSTOM_FORMAT constant variable.

levelint, optional

An integer value that specifies the logging level for the logger. Default is logger.DEBUG (equal to 10).

Returns:
logging.Logger

A new Logger object for logging any information or errors.

Raises:
JMUnknownTypeError

If the ‘fmt’ are not instance of str or logging.Formatter class.

jmbuilder.utils.json_parser(path: str) dict[source]#

Parse and retrieve all configurations from specified JSON configuration file.

Parameters:
pathstr

The path to specify the configuration file to be parsed.

Returns:
dict

A dictionary containing all parsed configurations from specified configuration file.

Raises:
JMParserError

If something went wrong during parsing the configuration file.

ValueError

If the given path is None.

JMUnknownTypeError

If the given path’s type are not str.

FileNotFoundError

If the given path are refers to a non-existing file.

IsADirectoryError

If the given path are refers to a directory instead a configuration file.

Notes

This function only supported configuration file with JSON type. Given file paths will be validated before retrieving their configurations, and check the extension file. Make sure the given path references to file with the .json extension.

jmbuilder.utils.remove_blanks(contents: List[str], none: bool = True) List[str][source]#

Remove empty lines from a list of strings.

This function removes empty lines (lines with no content) and lines containing only whitespace from the input list of strings. Optionally, it can removes lines containing None.

Parameters:
contentsList[str]

A list of strings representing the contents of a file.

nonebool, optional

If True, lines containing None are also removed. If False, only lines with no content are removed. The default is True.

Returns:
List[str]

A new contents with empty lines removed.

Raises:
ValueError

If the input list contents is empty.

jmbuilder.utils.remove_comments(contents: List[str], delim: str = '#') List[str][source]#

Remove lines starting with a specified delimiter.

This function removes lines from the input list of contents that start with the specified delimiter. It returns a new contents with comments removed.

Parameters:
contentsList[str]

A list of strings representing the contents of a file.

delimstr, optional

The delimiter used to identify comment lines. Lines starting with this delimiter will be removed. The default is ‘#’.

Returns:
List[str]

A new contents with comment lines (specified by delimiter) removed.

Raises:
ValueError

If the input list contents is empty.

Notes

Multiple specified delimiters cannot be removed in a single call to this function. Although the problem can be fixed by executing the procedure as many times depending on the delimiters that need to be removed. But still it is not a convenient way.

Examples:

# Suppose we want to remove lines that starting with
# hashtags (#) and exclamation marks (!).
>>> remove_comments(
...     remove_comments(contents, delim='#'), delim='!')

Submodules#

jmbuilder.utils.logger module#

Custom Logger Module for JMBuilder

This module provides a custom logger utility that initializes and creates a new Logger object for logging information or errors to the console or a log file.

To use the custom logger in your project, you can import the init_logger function from this module and create a new Logger object with desired settings.

Copyright (c) 2023-2024 Ryuu Mitsuki.

Available Functions#

init_logger

Initialize and create new Logger object for logging any information or errors to file, if specified, otherwise the output will be written to console standard error.

Available Constants#

BASIC_FORMATstr

The basic (default) format for logging.Formatter. This is alias for logging.BASIC_FORMAT.

CUSTOM_FORMATstr

The custom format for logging.Formatter.

CRITICALint

The integer value representation of logging level 50. This is alias for logging.CRITICAL.

DEBUGint

The integer value representation of logging level 10. This is alias for logging.DEBUG.

ERRORint

The integer value representation of logging level 40. This is alias for logging.ERROR.

FATALint

The integer value representation of logging level 50. This is alias for logging.FATAL.

INFOint

The integer value representation of logging level 20. This is alias for logging.INFO.

NOTSETint

The integer value of representation of logging level 0. This is alias for logging.NOTSET.

WARNint

The integer value of representation of logging level 30. This is alias for logging.WARN.

WARNINGint

The integer value of representation of logging level 30. This is alias for logging.WARNING.

Example#

# Import the module >>> from jmbuilder import logger

# Create a new logger object >>> log = logger.init_logger(fmt=logger.CUSTOM_FORMAT, … level=logger.INFO) >>> log <RootLogger root (INFO)> >>> type(log).__name__ ‘RootLogger’

# Log some information message # The output will be printed to console standard error (stderr), # because the filename are not defined on init_logger. >>> log.info(‘This is an information message.’) This is an information message.

# Log some exception # To trace the error, pass any true value to exc_info argument. >>> try: … x = 3 / 0 … except ZeroDivisionError as div_err: … log.error(‘An error occurred.’, exc_info=1) An error occurred. Traceback (most recent call last):

ZeroDivisionError: division by zero

jmbuilder.utils.logger.init_logger(filename: Optional[str] = None, *, fmt: Optional[Union[str, Formatter]] = None, level: int = 10) Logger[source]#

Initializes and creates a new Logger object.

Parameters:
filenamestr or None, optional

A string representing the name of the logger file. If specified, logs will be written to the specified file, otherwise logs will be printed to stderr (standard error). Default is None.

fmtstr or logging.Formatter, optional

A string representation of the log formatter or an object of logging.Formatter class. If not specified, a customized formatter will be used. See CUSTOM_FORMAT constant variable.

levelint, optional

An integer value that specifies the logging level for the logger. Default is logger.DEBUG (equal to 10).

Returns:
logging.Logger

A new Logger object for logging any information or errors.

Raises:
JMUnknownTypeError

If the ‘fmt’ are not instance of str or logging.Formatter class.

jmbuilder.utils.utils module#

Utilities Module for JMBuilder

This module provide utilities members, including JSON parser and properties parser for JMBuilder module.

Copyright (c) 2023-2024 Ryuu Mitsuki.

Available Classes#

JMProperties

A custom properties parser class, implemented in jmbuilder.utils package. Python does not provide an easy way to parsing files with extension of .properties, this class is designed to parse properties file and access their contents with ease without any third-party modules.

Available Functions#

json_parser

This utility function provides an easy way to parses and retrieves all configurations from JSON configuration files.

Examples:

>>> json_parser('path/to/configs_file.json')
{'foo': False, 'bar': True}
remove_comments

This utility function can remove lines from a list of strings representing the file contents that starting with a specified delimiter and returns a new list with lines starting with a specified delimiter removed. This function are designed for removing comments lines from file contents.

Examples:

# Read file contents
>>> contents = []
>>> with open('path/to/example.txt') as f:
...     contents = f.readlines()
...
>>> contents
['Hello', '# This is comment line', 'World']

>>> remove_comments(contents, delim='#')
['Hello', 'World']
remove_blanks

This utility function can remove blank lines from the list of strings representing the file contents, and optionally remove lines with value None. Return a new list with blank lines removed.

Examples:

>>> contents = ['', 'Foo', None, '', '1234']
>>> remove_blanks(contents, none=False)  # Ignore None
['Foo', None, '1234']

>>> remove_blanks(contents, none=True)
['Foo', '1234']
readfile

This utilty function will read the contents from the given file path and return a list containing all contents from that file.

If the given path does not refer to an existing regular file or the given path is refer to a directory, it will raises an error.

Examples:

# Read contents from file called 'myfile.txt'
>>> contents = readfile('myfile.txt')
class jmbuilder.utils.utils.JMProperties(filename: Union[str, TextIO], *, encoding: str = 'UTF-8')[source]#

Bases: UserDict

This class provides a convenient way to parse properties files and access their contents.

Parameters:
filenamestr or TextIO

The filename or file object to read properties from. If a filename is provided, it checks for the file’s existence, opens the file stream, and retrieves the properties. If a file object is provided, it directly reads the properties from it.

encodingstr, optional

The encoding to use when opening the file stream. If not specified, it uses the encoding from locale.getpreferredencoding(). Defaults to system’s preferred encoding.

Raises:
JMParserError

If an error occurs while reading and parsing the properties file.

FileNotFoundError

If the specified file path does not exist.

ValueError

If the filename parameter is None.

Attributes:
dataDict[str, str]

A dictionary containing all the parsed properties.

filenamestr

An absolute path to the specified property file.

Methods

clear()

get(k[,d])

items()

keys()

pop(k[,d])

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[,d])

update([E, ]**F)

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()

copy

fromkeys

_abc_impl = <_abc_data object>#
jmbuilder.utils.utils.json_parser(path: str) dict[source]#

Parse and retrieve all configurations from specified JSON configuration file.

Parameters:
pathstr

The path to specify the configuration file to be parsed.

Returns:
dict

A dictionary containing all parsed configurations from specified configuration file.

Raises:
JMParserError

If something went wrong during parsing the configuration file.

ValueError

If the given path is None.

JMUnknownTypeError

If the given path’s type are not str.

FileNotFoundError

If the given path are refers to a non-existing file.

IsADirectoryError

If the given path are refers to a directory instead a configuration file.

Notes

This function only supported configuration file with JSON type. Given file paths will be validated before retrieving their configurations, and check the extension file. Make sure the given path references to file with the .json extension.

jmbuilder.utils.utils.remove_blanks(contents: List[str], none: bool = True) List[str][source]#

Remove empty lines from a list of strings.

This function removes empty lines (lines with no content) and lines containing only whitespace from the input list of strings. Optionally, it can removes lines containing None.

Parameters:
contentsList[str]

A list of strings representing the contents of a file.

nonebool, optional

If True, lines containing None are also removed. If False, only lines with no content are removed. The default is True.

Returns:
List[str]

A new contents with empty lines removed.

Raises:
ValueError

If the input list contents is empty.

jmbuilder.utils.utils.remove_comments(contents: List[str], delim: str = '#') List[str][source]#

Remove lines starting with a specified delimiter.

This function removes lines from the input list of contents that start with the specified delimiter. It returns a new contents with comments removed.

Parameters:
contentsList[str]

A list of strings representing the contents of a file.

delimstr, optional

The delimiter used to identify comment lines. Lines starting with this delimiter will be removed. The default is ‘#’.

Returns:
List[str]

A new contents with comment lines (specified by delimiter) removed.

Raises:
ValueError

If the input list contents is empty.

Notes

Multiple specified delimiters cannot be removed in a single call to this function. Although the problem can be fixed by executing the procedure as many times depending on the delimiters that need to be removed. But still it is not a convenient way.

Examples:

# Suppose we want to remove lines that starting with
# hashtags (#) and exclamation marks (!).
>>> remove_comments(
...     remove_comments(contents, delim='#'), delim='!')