Package: lockup
API Documentation (stable)|API Documentation (current)|Code of Conduct|Contribution GuideOverviewEnables the creation of classes, modules, and namespaces on which the following
properties are true:All attributes areimmutable. Immutability increases code safety by
discouraging monkey-patching and preventing changes to state, accidental or
otherwise.>>>importgetpass>>>defsteal_password(prompt='Password: ',stream=None):...pwned=getpass.getpass(prompt=prompt,stream=stream)...# Send host address, username, and password to Dark Web collector....returnpwned...>>>importlockup>>>lockup.reclassify_module(getpass)>>>getpass.getpass=steal_passwordTraceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleAttributeOperation:Attempttoassignimmutableattribute'getpass'onmodule'getpass'.>>>importlockup>>>ns=lockup.create_namespace(some_constant=6)>>>ns.some_constant=13Traceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleAttributeOperation:Attempttoassignimmutableattribute'some_constant'onclass'lockup.Namespace'.Non-public attributes areconcealed. Concealment means that thedirfunction will
report a subset of attributes that are intended for programmers to use…
without exposing internals.>>>importlockup>>>classDemo(metaclass=lockup.Class):..._foo='Semi-private class variable.'...hello='Public class variable.'...def__len__(self):return1...>>>dir(Demo)['hello']In addition to the above, the package also provides the ability to apprehend
“fugitive” exceptions attempting to cross API boundaries. Various auxiliary
functionalities are provided as well; these are used internally within the
package but are deemed useful enough for public consumption. Please see the
documentation for more details.Quick TourModuleLet us consider the mutableosmodule from the Python standard library and how we can alter “constants” that
may be used in many places:>>>importos>>>type(os)<class'module'>>>>os.O_RDONLY0>>>os.O_RDONLY=os.O_RDWR>>>os.O_RDONLY2>>>os.O_RDONLY=0Now, let us see what protection it gains from becoming immutable:>>>importos>>>importlockup>>>lockup.reclassify_module(os)>>>type(os)<class'lockup.module.Module'>>>># How? https://docs.python.org/3/reference/datamodel.html#customizing-module-attribute-access>>>os.O_RDONLY=os.O_RDWRTraceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleAttributeOperation:Attempttoassignimmutableattribute'O_RDONLY'onmodule'os'.>>>delos.O_RDONLYTraceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleAttributeOperation:Attempttodeleteindelibleattribute'O_RDONLY'onmodule'os'.Class FactoryLet us monkey-patch a mutable class:>>>classA:...defexpected_functionality(self):return42...>>>a=A()>>>a.expected_functionality()42>>>defmonkey_patch(self):...return'I selfishly change behavior upon which other consumers depend.'...>>>A.expected_functionality=monkey_patch>>>a=A()>>>a.expected_functionality()'I selfishly change behavior upon which other consumers depend.'Now, let us try to monkey-patch an immutable class:>>>importlockup>>>classB(metaclass=lockup.Class):...defexpected_functionality(self):return42...>>>b=B()>>>b.expected_functionality()42>>>defmonkey_patch(self):...return'I selfishly change behavior upon which other consumers depend.'...>>>B.expected_functionality=monkey_patchTraceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleAttributeOperation:Attempttoassignimmutableattribute'expected_functionality'onclass...>>>delB.expected_functionalityTraceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleAttributeOperation:Attempttodeleteindelibleattribute'expected_functionality'onclass...NoteOnly class attributes are immutable. Instances of immutable classes will
have mutable attributes without additional intervention beyond the scope of
this package.Namespace FactoryAn alternative totypes.SimpleNamespaceis
provided. First, let us observe the behaviors on a standard namespace:>>>importtypes>>>sn=types.SimpleNamespace(run=lambda:42)>>>snnamespace(run=<function<lambda>at...>)>>>sn.run()42>>>type(sn)<class'types.SimpleNamespace'>>>>sn.__dict__{'run':<function<lambda>at...>}>>>type(sn.run)<class'function'>>>>sn.run=lambda:666>>>sn.run()666>>>sn()# doctest: +SKIPTraceback(mostrecentcalllast):...TypeError:'types.SimpleNamespace'objectisnotcallableNow, let us compare those behaviors to an immutable namespace:>>>importlockup>>>ns=lockup.create_namespace(run=lambda:42)>>>nsNamespaceClass('Namespace',('object',),{...})>>>ns.run()42>>>type(ns)<class'lockup.factories.NamespaceClass'>>>>ns.__dict__mappingproxy({...})>>>type(ns.run)<class'function'>>>>ns.run=lambda:666Traceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleAttributeOperation:Attempttoassignimmutableattribute'run'onclass'lockup.Namespace'.>>>ns.__dict__['run']=lambda:666Traceback(mostrecentcalllast):...TypeError:'mappingproxy'objectdoesnotsupportitemassignment>>>ns()Traceback(mostrecentcalllast):...lockup.exceptions.ImpermissibleOperation:Impermissibleinstantiationofclass'lockup.Namespace'.Also of note is that we can define namespace classes directly, allowing us to
capture imports for internal use in a module without publicly exposing them as
part of the module API, for example:>>>importlockup>>>class__(metaclass=lockup.NamespaceClass):...fromosimportO_RDONLY,O_RDWR...>>>__.O_RDONLY0The above technique is used internally within this package itself.InterceptionIf a particular exceptional condition is not anticipated in Python code, a
“fugitive” exception can escape across the boundary of a published API. If you
have told the consumers of the API that it will only emit certain classes of
exceptions, then consumers might not handle exceptions outside of the expected
classes, i.e., fugitive exceptions. If you apprehend all fugitives at the API
boundary, then you can guarantee to your consumers that they will only need to
anticipate certain classes of exceptions.Here is an example with an interceptor, which includes fugitive exception
apprehension, that this package uses internally:>>>fromlockup.exceptionsimportInvalidState>>>fromlockup.interceptionimportour_interceptor>>>@our_interceptor...defdivide_by_zero(number):returnnumber/0...>>>try:divide_by_zero(42)...exceptInvalidStateasexc:...type(exc),type(exc.__cause__),str(exc)...(<class'lockup.exceptions.InvalidState'>, <class 'ZeroDivisionError'>, "Apprehension of fugitive exception of class 'builtins.ZeroDivisionError' at boundary of function 'divide_by_zero' on module '__main__'.")As can be seen, theZeroDivisionErroris in the custody of an exception
that is of an expected class.You can create your own interceptors with custom fugitive apprehension
behaviors using thecreate_interception_decoratorfunction.CompatibilityThis package has been verified to work on the following Python implementations:CPythonComplete functionality.Support for interpreters compiled withPy_TRACE_REFSdefinition.PyPyComplete functionality except for reflection.Reflection is a no-op ifassert_implementationisFalse.PystonComplete functionality.WarningSupport for Pyston may disappear in the future as the maintainers have
decided to invest in a JIT module for CPython rather than a separate
implementation.It likely works on others as well, but please report if it does not.More Flair…than the required minimumChangelogv2.1.0Python SupportRemove Pyston because its maintainers have decided upon another direction.
Thereflectionmodule still recognizes Pyston, but there is no support
for this Python implementation, going forward.Add CPython 3.11.v2.0.0APINo more separate API for package-internal development. Everything is now
exposed as part of an auxiliary public API as opposed to the primary public
API.NoteSome parts of the auxiliary public API may be refactored into separate
packages at a later point.Providecreate_interception_decoratorfunction which creates function
decorators that can apprehend “fugitive” exceptions before they escape across
the boundary of a public API. Fugitive exceptions are exceptions which are
unexpected and which should have been caught internally.Providereassign_class_factoryfunction which allows for a class to be
assigned a new factory class (“metaclass”). This can even be used on a class
factory class itself, resulting in a factory class similar to howtypebehaves. This
package uses it internally, when possible, to allow class factory classes to
enforce attribute concealment and immutability on themselves and not just
their instances. But, it can be put to other purposes too.Provide exception management utilities, including factories which can inject
labels into instances of a single omniexception class as an alternative to
working with a class hierarchy. This package internally uses the utilities to
create exceptions with descriptive messages and labels.Provide nomenclatural utilities which determine the classification of objects
that are provided to them. These are useful for the creation of more helpful
exception messages or log entries. This package internally uses the utilities
to create descritpive exception messages. A suite of exception factories,
which use these utilities, is also exposed.Provide validation utilities which return back their argument if the
validation is successful. Otherwise, they raise a validation error. This
allows for multiple validators to be fluently applied in succession. This
package internally uses the validators on arguments to functions that are
part of its public API.Provide visibility utilities which determine if an attribute is considered
public or non-public and what attributes should be concealed on an object.
This package uses the utilities internally to conceal non-public attributes
on classes, modules, and namespaces. But, they can be put to other purposes
as well.Python SupportRemove CPython 3.6 because it is past end-of-life.Deprecate Pyston because of its new development direction.Add PyPy 3.9.v1.1.0DocumentationOfficially verify and mention PyPy and Pyston support.