Package: pyTooling
pyToolingpyToolingis a powerful collection of arbitrary useful abstract data models, missing classes, decorators, a new
performance boosting meta-class and enhanced exceptions. It also provides lots of helper functions e.g. to ease the
handling of package descriptions or to unify multiple existing APIs into a single API.It's useful - if not even essential - foranyPython-base project independent if it's a library, framework, CLI tool
or just a "script".In addition, pyTooling provides a collection ofCI job templates for GitHub Actions.
This drastically simplifies GHA-based CI pipelines for Python projects.Package DetailsAttributesThe [pyTooling.Attributes] module offers the base implementation of.NET-like attributesrealized with Python
decorators. The annotated and declarative data is stored as instances of Attribute classes in an additional field per
class, method or function.The annotation syntax (decorator syntax) allows users to attach any structured data to classes, methods or functions. In
many cases, a user will derive a custom attribute from Attribute and override theinitmethod, so user-defined
parameters can be accepted when the attribute is constructed.Later, classes, methods or functions can be searched for by querying the attribute class for attribute instance usage
locations (see example to the right). Another option for class and method attributes is declaring a classes using
pyTooling’sExtendedTypemeta-class. Here the class itself offers helper methods for discovering annotated methods.ASimpleAttributeclass is offered accepting any positional and keyword parameters. In a more advanced use case, users
are encouraged to derive their own attribute class hierarchy fromAttribute.Use CasesIn general all classes, methods and functions can be annotated with additional meta-data. It depends on the application,
framework or library to decide if annotations should be applied imperatively as regular code or declaratively as
attributes via Python decorators.With this in mind, the following use-cases and ideas can be derived:Describe a command line argument parser (like ArgParse) in a declarative form. |br|
SeepyTooling.Attributes.ArgParse Package and ExamplesMark nested classes, so later when the outer class gets instantiated, these nested classes are indexed or
automatically registered.SeeCLIAbstraction→ [CLIABS/CLIArgument]Mark methods in a class as test cases and classes as test suites, so test cases and suites are not identified based on
a magic method name.Investigation ongoing / planned feature.UsingSimpleAttributefrompyTooling.AttributesimportSimpleAttribute@SimpleAttribute(kind="testsuite")classMyClass:@SimpleAttribute(kind="testcase",id=1,description="Test and operator")deftest_and(self):...@SimpleAttribute(kind="testcase",id=2,description="Test xor operator")deftest_xor(self):...CLI Abstraction[pyTooling.CLIAbstraction] offers an abstraction layer for command line programs, so they can be used easily in Python.
There is no need for manually assembling parameter lists or considering the order of parameters. All parameters like-vor--value=42are described as [CommandLineArgument] instances on a [Program] class. Each argument class like
[ShortFlag] or [PathArgument] knows about the correct formatting pattern, character escaping, and if needed about
necessary type conversions. A program instance can be converted to an argument list suitable for [subprocess.Popen].While a user-defined command line program abstraction derived from [Program] only
takes care of maintaining and assembling parameter lists, a more advanced base-class, called [Executable],
is offered with embedded [subprocess.Popen] behavior.Design GoalsOffer access to CLI programs as Python classes.Abstract CLI arguments (a.k.a. parameter, option, flag, ...) as members on such a Python class.Abstract differences in operating systems like argument pattern (POSIX:-hvs. Windows:/h), path delimiter
signs (POSIX:/vs. Windows:\) or executable names.Derive program variants from existing programs.Assemble parameters as list for handover to [subprocess.Popen] with proper escaping and quoting.Launch a program with :class:[subprocess.Popen] and hide the complexity of Popen.Get a generator object for line-by-line output reading to enable postprocessing of outputs.Common Helper FunctionsThis is a set of usefulhelper functions:getsizeofcalculates the "real" size of a data structure.isnestedclasschecks if a class is nested inside another class.firstKey,firstValue,firstPairget the firstItem key/value/item from an ordered dictionary.mergedictsmerges multiple dictionaries into a new dictionary.zipdictsiterate multiple dictionaries simultaneously.Common ClassesCall-by-reference parameters: Python doesn't providecall-by-reference parametersfor simple types.This behavior can be emulated with classes provided by thepyTooling.CallByRefmodule.Unified license names: Setuptools, PyPI, and others
have a varying understanding of license names.ThepyTooling.Licensingmodule providesunified license namesas well as license name mappings or translations.Unified platform and environment description: Python has
many ways in figuring out the current platform using APIs fromsys,platform,os, …. Unfortunately, none of the
provided standard APIs offers a comprehensive answer. pyTooling provides aCurrentPlatformsingleton summarizing
multiple platform APIs into a single class instance.Representations of version numbers: While Python
itself has a good versioning schema, there are no classes provided to abstract version numbers. pyTooling provides
such representations following semantic versioning (SemVer) and calendar versioning (CalVer) schemes. It's provided by
thepyTooling.Versioningmodule.ConfigurationVarious file formats suitable for configuration information share the same features supporting: key-value pairs
(dictionaries), sequences (lists), and simple types like string, integer and float. pyTooling provides anabstract configuration file data modelsupporting
these features. Moreover, concreteconfiguration file format readerimplementations are provided as well.JSON configuration readerfor the JSON file format.TOML configuration reader→ To be implemented.YAML configuration readerfor the YAML file format.Data StructurespyTooling also providesfast and powerful data structuresoffering object-oriented APIs:Graph data structure→ A directed graph implementation using aVertexand anEdgeclass.Path data structure→ To be documented.Finite State Machine data structure→ A data model for state machines using aStateand aTransitionclass.Tree data structure→ A fast and simple implementation using a singleNodeclass.DecoratorsAbstract MethodsMethods marked withabstractmethodare abstract and need to be overwritten in a derived class.Anabstract methodmight be called from the overwriting method.Methods marked withmustoverrideare abstract and need to be overridden in a derived class.It's not allowed to call amustoverride method.DocumentationCopy the doc-string from given base-class viaInheritDocString.VisibilityRegister the given function or class as publicly accessible in a module viaexport.Documentation@InheritDocString→ Copy the doc-string from given base-class.Visibility@export→ Register the given function or class as publicly accessible in a module.ExceptionsEnvironmentException... is raised when an expected environment variable is missing.PlatformNotSupportedException... is raise if the platform is not supported.NotConfiguredException... is raise if the requested setting is not configured.Meta-ClassespyTooling provides anenhanced meta-classcalledExtendedType. This meta-classes allows to implementabstract methods,singletons,slotted typesand combinations thereof.class MyClass(metaclass=ExtendedType):A class definition using that meta-class can implementabstract methodsusing decorators@abstractmethodor@mustoverride.class MyClass(metaclass=ExtendedType, singleton=True):A class defined with enabledsingletonbehavior
allows only a single instance of that class to exist. If another instance is going to be created, a previously cached
instance of that class will be returned.class MyClass(metaclass=ExtendedType, slots=True):A class defined with enabledslotsbehavior
stores instance fields in slots. The meta-class, translates all type-annotated fields in a class definition into
slots. Slots allow a more efficient field storage and access compared to dynamically stored and accessed fields hosted
by__dict__. This improves the memory footprint as well as the field access performance of all class instances. This
behavior is automatically inherited to all derived classes.class MyClass(ObjectWithSlots):A class definition deriving fromObjectWithSlotswill bring the slotted type behavior to that class and all derived
classes.PackagingA set of helper functions to describe a Python package for setuptools.Helper Functions:loadReadmeFileLoad aREADME.mdfile from disk and provide the content as long description for setuptools.loadRequirementsFileLoad arequirements.txtfile from disk and provide the content for setuptools.extractVersionInformationExtract version information from Python source files and provide the data to setuptools.Package DescriptionsDescribePythonPackagetbdDescribePythonPackageHostedOnGitHubtbdTerminalA set of helpers to implement a text user interface (TUI) in a terminal.FeaturesColored command line outputs based oncolorama.Message classification infatal,error,warning,normal,quiet, ...Get information like terminal dimensions from underlying terminal window.Simple Terminal ApplicationThis is a minimal terminal application example which inherits fromLineTerminal.frompyTooling.TerminalUIimportTerminalApplicationclassApplication(TerminalApplication):def__init__(self)->None:super().__init__()defrun(self):self.WriteNormal("This is a simple application.")self.WriteWarning("This is a warning message.")self.WriteError("This is an error message.")# entry pointif__name__=="__main__":Application.CheckPythonVersion((3,6,0))app=Application()app.run()app.Exit()TimertbdExamples@exportDecoratorfrompyTooling.Decoratorsimportexport@exportclassMyClass:passCallByRefIntParamfrompyTooling.CallByRefimportCallByRefIntParam# define a call-by-reference parameter for integer valuesmyInt=CallByRefIntParam(3)# a function using a call-by-reference parameterdeffunc(param:CallByRefIntParam):param<<=param*4# call the function and pass the wrapper objectfunc(myInt)print(myInt.Value)ContributorsPatrick Lehmann(Maintainer)Sven KöhlerUnai Martinez-Corraland more...LicenseThis Python package (source code) licensed underApache License 2.0.The accompanying documentation is licensed underCreative Commons - Attribution 4.0 (CC-BY 4.0).SPDX-License-Identifier: Apache-2.0