API Reference¶
Config¶
-
forge.get_run_validators() → bool¶ Check whether validators are enabled. :returns: whether or not validators are run.
-
forge.set_run_validators(run: bool) → None¶ Set whether or not validators are enabled. :param _sphinx_paramlinks_forge.set_run_validators.run: whether the validators are run
Exceptions¶
-
class
forge.ForgeError¶ A common base class for
forgeexceptions
-
class
forge.ImmutableInstanceError¶ An error that is raised when trying to set an attribute on a
Immutableinstance.
Marker¶
-
class
forge.empty¶ A simple
MarkerMetaclass useful for denoting that no input was suplied. Used in place ofinspect.Parameter.emptyas that is not repr’d (providing confusing usage).Usage:
def proxy(a, b, extra=empty): if extra is not empty: return proxied(a, b) return proxied(a, b, c=inspect.Parameter.empty)
-
classmethod
ccoerce_native(value)¶ Conditionally coerce the value to a non-
emptyvalue.Parameters: value¶ – the value to conditionally coerce Returns: the value, if the value is not an instance of empty, otherwise returninspect.Paramter.empty
-
classmethod
ccoerce_synthetic(value)¶ Conditionally coerce the value to a non-
inspect.Parameter.emptyvalue.Parameters: value¶ – the value to conditionally coerce Returns: the value, if the value is not an instance of inspect.Paramter.empty, otherwise returnempty
-
native¶ alias of
inspect._empty
-
classmethod
-
class
forge.void¶ A simple
MarkerMetaclass useful for denoting that no input was suplied.Usage:
def proxy(a, b, extra=void): if extra is not void: return proxied(a, b) return proxied(a, b, c=extra)
Revisions¶
-
class
forge.Mapper(fsignature: forge._signature.FSignature, callable: Callable[..., Any])¶ An immutable data structure that provides the recipe for mapping an
FSignatureto an underlying callable.Parameters: - fsignature¶ – an instance of
FSignaturethat provides the public and private interface. - callable¶ – a callable that ultimately receives the arguments provided
to public
FSignatureinterface.
Variables: - callable – see
callable - fsignature – see
fsignature - parameter_map – a
types.MappingProxythat exposes the strategy of how to map from theMapper.fsignatureto theMapper.callable - private_signature – a cached copy of
callable’sinspect.Signature - public_signature – a cached copy of
fsignature’s manifest as ainspect.Signature
-
get_context(arguments: Mapping) → Any¶ Retrieves the context arguments value (if a context parameter exists)
Parameters: arguments¶ – a mapping of parameter names to argument values Returns: the argument value for the context parameter (if it exists), otherwise None.
-
static
map_parameters(from_: forge._signature.FSignature, to_: inspect.Signature) → mappingproxy¶ Build a mapping of parameters from the
Mapper.map_parameters.from_to theMapper.map_parameters.to_.Strategy rules: #. every to_ positional-only must be mapped to #. every to_ positional-or-keyword w/o default must be mapped to #. every to_ keyword-only w/o default must be mapped to #. from_ var-positional requires to_ var-positional #. from_ var-keyword requires to_ var-keyword
Parameters: - from_¶ – the
FSignatureto map from - to_¶ – the
inspect.Signatureto map to
Returns: a
types.MappingProxyTypethat shows how arguments are mapped.- from_¶ – the
- fsignature¶ – an instance of
-
class
forge.Revision¶ This is a base class for other revisions. It implements two methods of primary importance:
revise()and__call__().Revisions can act as decorators, in which case the callable is wrapped in a function that translates the supplied arguments to the parameters the underlying callable expects:
import forge @forge.Revision() def myfunc(): pass
Revisions can also operate on
FSignatureinstances directly by providing anFSignaturetorevise():import forge in_ = forge.FSignature() out_ = forge.Revision().revise(in_) assert in_ == out_
The
revise()method is expected to return an instance ofFSignaturethat is not validated. This can be achieved by supplying__validate_attributes__=Falseto eitherFSignatureorreplace().Instances of
Revisiondon’t have any initialization parameters or public attributes, but subclasses instances often do.-
__call__(callable: Callable[..., Any]) → Callable[..., Any]¶ Wraps a callable with a function that maps the new signature’s parameters to the original function’s signature.
If the function was already wrapped (has an
__mapper__attribute), then the (underlying) wrapped function is re-wrapped.Parameters: callable¶ – a callable whose signature to revise Returns: a function with the revised signature that calls into the provided callable
-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Applies the identity revision:
previousis returned unmodified.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
-
Group revisions¶
-
class
forge.compose(*revisions)¶ Batch revision that takes
Revisioninstances and applies theirrevise()usingfunctools.reduce().Parameters: revisions¶ – instances of Revision, used to revise theFSignature.-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Applies
revisionsNo validation is explicitly performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context of (another)compose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
-
-
class
forge.copy(callable: Callable[..., Any], *, include: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool], NoneType] = None, exclude: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool], NoneType] = None)¶ The
copyrevision takes a callable and optionally parameters to include or exclude, and applies the resultant signature.Parameters: - callable¶ – a callable whose signature is copied
- include¶ – a string, iterable of strings, or a function that receives
an instance of
FParameterand returns a truthy value whether to include it. - exclude¶ – a string, iterable of strings, or a function that receives
an instance of
FParameterand returns a truthy value whether to exclude it.
Raises: TypeError – if
includeandexcludeare provided-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Copies the signature of
callable. If provided, only a subset of parameters are copied, as determiend byincludeandexclude.Unlike most subclasses of
Revision, validation is performed on the updatedFSignature. This is becausecopytakes a callable which is required by Python to have a valid signature, so it’s impossible to return an invalid signature.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
-
class
forge.manage(callable: Callable[forge._signature.FSignature, forge._signature.FSignature])¶ Revision that revises a
FSignaturewith a user-supplied revision function.import forge def reverse(previous): return previous.replace( parameters=previous[::-1], __validate_parameters__=False, ) @forge.manage(reverse) def func(a, b, c): pass assert forge.repr_callable(func) == 'func(c, b, a)'
Parameters: callable¶ – a callable that alters the previous signature -
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Passes the signature to
callablefor revision.Warning
No validation is typically performed in the
revisemethod. Consider providing False as an argument value to__validate_parameters__, so that this revision can be used within the context of acomposerevision.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
-
-
class
forge.returns(type: Any = <empty>)¶ The
returnsrevision updates a signature’sreturn-typeannotation.import forge @forge.returns(int) def x(): pass assert forge.repr_callable(x) == "x() -> int"
Parameters: type¶ – the return typefor the factoryVariables: return_annotation – the return typeused for revising signatures-
__call__(callable: Callable[..., Any]) → Callable[..., Any]¶ Changes the return value of the supplied callable. If the callable is already revised (has an
__mapper__attribute), then thereturn typeannoation is set without wrapping the function. Otherwise, the__mapper__and__signature__are updatedParameters: callable¶ – see callableReturns: either the input callable with an updated return type annotation, or a wrapping function with the appropriate return type annotation as determined by the strategy described above.
-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Applies the return type annotation,
return_annotation, to the input signature.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
-
-
class
forge.synthesize(*parameters, **named_parameters)¶ Revision that builds a new signature from instances of
FParameterOrder parameters with the following strategy:
- arguments are returned in order
- keyword arguments are sorted by
_creation_order, and evolved with thekeywordvalue as the name and interface_name (if not set).
Warning
When supplying previously-created parameters to
sign(), those parameters will be ordered by their creation order.This is because Python implementations prior to
3.7don’t guarantee the ordering of keyword-arguments.Therefore, it is recommended that when supplying pre-created parameters to
sign(), you supply them as positional arguments:import forge param_b = forge.arg('b') param_a = forge.arg('a') @forge.sign(a=param_a, b=param_b) def func1(**kwargs): pass @forge.sign(param_a, param_b) def func2(**kwargs): pass assert forge.repr_callable(func1) == 'func1(b, a)' assert forge.repr_callable(func2) == 'func2(a, b)'
Parameters: - parameters¶ –
FParameterinstances to be ordered - named_parameters¶ –
FParameterinstances to be ordered, updated
Returns: a wrapping factory that takes a callable and returns a wrapping function that has a signature as defined by the
parametersandnamed_parameters-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Produces a signature with the parameters provided at initialization.
No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
-
forge.sign¶ a convenience “short-name” for
synthesize
-
class
forge.sort(sortkey: Union[typing.Callable[[forge._signature.FParameter], typing.Any], NoneType] = None)¶ Revision that orders parameters. The default orders parameters ina common- sense way:
- parameter kind, then
- parameters having a default value
- parameter name lexicographically
import forge @forge.sort() def func(c, b, a): pass assert forge.repr_callable(func) == 'func(a, b, c)'
Parameters: sortkey¶ – a function provided to the builtin sorted(). Receives instances ofFParameter, and should return a key to sort on.-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Applies the sorting
return_annotation, to the input signature.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
Unit revisions¶
-
class
forge.delete(selector: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool]], multiple: bool = False, raising: bool = True)¶ Revision that deletes one (or more) parameters from an
FSignature.Parameters: - selector¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to exclude it. - multiple¶ – whether to delete all parameters that match the
selector - raising¶ – whether to raise an exception if the
selectormatches no parameters
-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Deletes one or more parameters from
previousbased on instance attributes.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
- selector¶ – a string, iterable of strings, or a function that
receives an instance of
-
class
forge.insert(insertion: Union[forge._signature.FParameter, typing.Iterable[forge._signature.FParameter]], *, index: int = None, before: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool]] = None, after: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool]] = None)¶ Revision that inserts a new parameter into a signature at an index, before a selector, or after a selector.
import forge @forge.insert(forge.arg('a'), index=0) def func(b, **kwargs): pass assert forge.repr_callable(func) == 'func(a, b, **kwargs)'
Parameters: - insertion¶ – the parameter or iterable of parameters to insert
- index¶ – the index to insert the parameter into the signature
- before¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to place the provided parameter before it. - after¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to place the provided parameter before it.
-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Inserts the
insertioninto a signature.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
-
class
forge.modify(selector: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool]], multiple: bool = False, raising: bool = True, *, kind=<void>, name=<void>, interface_name=<void>, default=<void>, factory=<void>, type=<void>, converter=<void>, validator=<void>, bound=<void>, contextual=<void>, metadata=<void>)¶ Revision that modifies one or more parameters.
import forge @forge.modify('a', kind=forge.FParameter.POSITIONAL_ONLY) def func(a): pass assert forge.repr_callable(func) == 'func(a, /)'
Parameters: - selector¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to place the provided parameter before it. - multiple¶ – whether to delete all parameters that match the
selector - raising¶ – whether to raise an exception if the
selectormatches no parameters - kind¶ – see
kind - name¶ – see
name - interface_name¶ – see
interface_name - default¶ – see
default - factory¶ – see
factory - type¶ – see
type - converter¶ – see
converter - validator¶ – see
validator - bound¶ – see
bound - contextual¶ – see
contextual - metadata¶ – see
metadata
-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Revises one or more parameters that matches
selector.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
- selector¶ – a string, iterable of strings, or a function that
receives an instance of
-
class
forge.replace(selector: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool]], parameter: forge._signature.FParameter)¶ Revision that replaces a parameter.
import forge @forge.replace('a', forge.kwo('b', 'a')) def func(a): pass assert forge.repr_callable(func) == 'func(*, b)'
Parameters: - selector¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to place the provided parameter before it. - parameter¶ – an instance of
FParameterto replace the selected parameter with.
-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Replaces a parameter that matches
selector.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
- selector¶ – a string, iterable of strings, or a function that
receives an instance of
-
class
forge.translocate(selector, *, index=None, before=None, after=None)¶ Revision that translocates (moves) a parameter to a new position in a signature.
import forge @forge.translocate('a', index=1) def func(a, b): pass assert forge.repr_callable(func) == 'func(b, a)'
Parameters: - selector¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to place the provided parameter before it. - index¶ – the index to insert the parameter into the signature
- before¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to place the provided parameter before it. - after¶ – a string, iterable of strings, or a function that
receives an instance of
FParameterand returns a truthy value whether to place the provided parameter before it.
-
revise(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Translocates (moves) the
parameterinto a new position in the signature.No validation is performed on the updated
FSignature, allowing it to be used as an intermediate revision in the context ofcompose.Parameters: previous¶ – the FSignatureto modifyReturns: a modified instance of FSignature
- selector¶ – a string, iterable of strings, or a function that
receives an instance of
-
forge.move¶ a convenience “short-name” for
translocate
Signature¶
Classes¶
-
class
forge.FSignature(parameters: Union[typing.Iterable[forge._signature.FParameter], NoneType] = None, *, return_annotation: Any, __validate_parameters__: bool = False)¶ An immutable, validated representation of a signature composed of
FParameterinstances, and a return type annotation.Sequence methods are supported and
__getitem__is overloaded to provide access to parameters by index, name, or a slice. Described in further detail:__getitem__()Parameters: - parameters¶ – an iterable of
FParameterthat makes up the signature - return_annotation¶ – the return type annotation for the signature
- __validate_parameters__¶ – whether the sequence of provided parameters should be validated
-
classmethod
from_callable(callable: Callable) → forge._signature.FSignature¶ A factory method that creates an instance of
FSignaturefrom a callable. Calls down tofrom_native()to do the heavy loading.Parameters: callable¶ – a callable from which to derive the FSignatureReturns: an instance of FSignaturederived from thecallableargument.
-
classmethod
from_native(signature: inspect.Signature) → forge._signature.FSignature¶ A factory method that creates an instance of
FSignaturefrom an instance ofinspect.Signature. Calls down toFParameterto map theinspect.Signature.parameterstoinspect.Parameterinstances.The
return typeannotation from the provided signature is not retained, asfrom_native()doesn’t provide this functionality.Parameters: signature¶ – an instance of inspect.Signaturefrom which to derive theFSignatureReturns: an instance of FSignaturederived from thesignatureargument.
-
native¶ Provides a representation of this
FSignatureas an instance ofinspect.Signature
-
parameters¶ The signature’s
~forge.FParameter
-
replace(*, parameters=<void>, return_annotation=<void>, __validate_parameters__=True) → forge._signature.FSignature¶ Returns a copy of this
FSignaturewith replaced attributes.Parameters: - parameters¶ – see
parameters - return_annotation¶ – see
return_annotation - __validate_parameters__¶ – see
__validate_parameters__
Returns: a new copy of
FSignaturerevised with replacements- parameters¶ – see
-
validate()¶ Validation ensures:
the appropriate order of parameters by kind:
- (optional) positional-only, followed by
- (optional) positional-or-keyword, followed by
- (optional) var-positional, followed by
- (optional) keyword-only, followed by
- (optional) var-keyword
- that non-default positional-only or
positional-or-keyword parameters don’t follow their respective similarly-kinded parameters with defaults,
Note
Python signatures allow non-default keyword-only parameters to follow default keyword-only parameters.
that at most there is one var-positional parameter,
that at most there is one var-keyword parameter,
- that at most there is one
contextparameter, and that it is the first parameter (if it is provided.)
- that at most there is one
- that no two instances of
FParametershare the same nameorinterface_name.
- that no two instances of
- parameters¶ – an iterable of
-
class
forge.FParameter(kind: inspect._ParameterKind, name: Union[str, NoneType] = None, interface_name: Union[str, NoneType] = None, default: Any = <empty>, factory: Callable[Any] = <empty>, type: Any = <empty>, converter: Union[typing.Callable[[typing.Any, str, typing.Any], typing.Any], typing.Iterable[typing.Callable[[typing.Any, str, typing.Any], typing.Any]], NoneType] = None, validator: Union[typing.Callable[[typing.Any, str, typing.Any], typing.Any], typing.Iterable[typing.Callable[[typing.Any, str, typing.Any], typing.Any]], NoneType] = None, bound: bool = False, contextual: bool = False, metadata: Union[typing.Mapping, NoneType] = None)¶ An immutable representation of a signature parameter that encompasses its public name, its interface name, transformations to be applied, and associated meta-data that defines its behavior in a signature.
Note
This class doesn’t need to be invoked directly. Use one of the constructor methods instead:
pos()for positional-onlyFParameterpok()orarg()for positional-or-keywordFParametervpo()for var-positionalFParameterkwo()orkwarg()for keyword-onlyFParametervkw()for var-keywordFParameter
Parameters: - kind¶ – the parameter kind, which detemrines the position of the parameter in a callable signature.
- name¶ – the public name of the parameter.
For example, in
f(x)->g(y),nameisx. - interface_name¶ – the name of mapped-to the parameter.
For example, in
f(x)->g(y),interface_nameisy. - default¶ – the default value for the parameter.
Cannot be supplied alongside a
factoryargument. For example, to achievef(x=3), specify :code`default=3`. - factory¶ – a function that generates a default for the parameter
Cannot be supplied alongside a
defaultargument. For example, to achievef(x=<Factory now>), specifyfactory=default.now(notice: without parentheses). - type¶ – the type annotation of the parameter.
For example, to achieve
f(x: int),typeisint. - converter¶ – a callable or iterable of callables that receive a
ctxargument, anameargument and avalueargument for transforming inputs. - validator¶ – a callable that receives a
ctxargument, anameargument and avalueargument for validating inputs. - bound¶ – whether the parameter is visible in the signature
(requires
defaultorfactoryif True) - contextual¶ – whether the parameter will be passed to
converterandvalidatorcallables as the context (only the first parameter in aFSignaturecan be contextual) - metadata¶ – optional, extra meta-data that describes the parameter
Variables: - POSITIONAL_ONLY – the positional-only
parameter kind constant
inspect.Parameter.POSITIONAL_ONLY - POSITIONAL_OR_KEYWORD – the positional-or-keyword
parameter kind constant
inspect.Parameter.POSITIONAL_OR_KEYWORD - VAR_POSITIONAL – the var-positional constant
parameter kind constant
inspect.Parameter.VAR_POSITIONAL - KEYWORD_ONLY – the keyword-only constant
parameter kind constant
inspect.Parameter.KEYWORD_ONLY - VAR_KEYWORD – the var-keyword constant
parameter kind constant
inspect.Parameter.VAR_KEYWORD
-
apply_conversion(ctx: Any, value: Any) → Any¶ Apply a transform or series of transforms against the argument value with the callables from
converter.Parameters: - ctx¶ – the context of this parameter as provided by the
FSignature(typically self or ctx). - value¶ – the argument value for this parameter
Returns: the converted value
- ctx¶ – the context of this parameter as provided by the
-
apply_default(value: Any) → Any¶ Return the argument value (if not
empty), or the value fromdefault(if not an instance ofFactory), or the value obtained by callingdefault(if an instance ofFactory).Parameters: value¶ – the argument value for this parameter Returns: the input value or a default value
-
apply_validation(ctx: Any, value: Any) → Any¶ Apply a validation or series of validations against the argument value with the callables from
validator.Parameters: - ctx¶ – the context of this parameter as provided by the
FSignature(typically self or ctx). - value¶ – the value the user has supplied or a default value
Returns: the (unchanged) validated value
- ctx¶ – the context of this parameter as provided by the
-
classmethod
create_contextual(name=None, interface_name=None, *, type=<empty>, metadata=None) → forge._signature.FParameter¶ A factory method for creating positional-or-keyword
FParameterinstances that arecontextual(this value is passed to otherFParameter`s ``converter`andvalidatorfunctions.)Parameters:
-
classmethod
create_keyword_only(name=None, interface_name=None, *, default=<empty>, factory=<empty>, type=<empty>, converter=None, validator=None, bound=False, metadata=None) → forge._signature.FParameter¶ A factory method for creating keyword-only
FParameterinstances.Parameters:
-
classmethod
create_positional_only(name=None, interface_name=None, *, default=<empty>, factory=<empty>, type=<empty>, converter=None, validator=None, bound=False, metadata=None) → forge._signature.FParameter¶ A factory method for creating positional-only
FParameterinstances.Parameters:
-
classmethod
create_positional_or_keyword(name=None, interface_name=None, *, default=<empty>, factory=<empty>, type=<empty>, converter=None, validator=None, bound=False, metadata=None) → forge._signature.FParameter¶ A factory method for creating positional-or-keyword
FParameterinstances.Parameters:
-
classmethod
create_var_keyword(name, *, type=<empty>, converter=None, validator=None, metadata=None) → forge._signature.FParameter¶ A factory method for creating var-keyword
FParameterinstances.Parameters:
-
classmethod
create_var_positional(name, *, type=<empty>, converter=None, validator=None, metadata=None) → forge._signature.FParameter¶ A factory method for creating var-positional
FParameterinstances.Parameters:
-
class
empty¶ A simple
MarkerMetaclass useful for denoting that no input was suplied. Used in place ofinspect.Parameter.emptyas that is not repr’d (providing confusing usage).Usage:
def proxy(a, b, extra=empty): if extra is not empty: return proxied(a, b) return proxied(a, b, c=inspect.Parameter.empty)
-
classmethod
ccoerce_native(value)¶ Conditionally coerce the value to a non-
emptyvalue.Parameters: value¶ – the value to conditionally coerce Returns: the value, if the value is not an instance of empty, otherwise returninspect.Paramter.empty
-
classmethod
ccoerce_synthetic(value)¶ Conditionally coerce the value to a non-
inspect.Parameter.emptyvalue.Parameters: value¶ – the value to conditionally coerce Returns: the value, if the value is not an instance of inspect.Paramter.empty, otherwise returnempty
-
native¶ alias of
inspect._empty
-
classmethod
-
classmethod
from_native(native: inspect.Parameter) → forge._signature.FParameter¶ A factory method for creating
FParameterinstances frominspect.Parameterinstances.Parameter descriptions are a subset of those defined on
FParameterParameters: native¶ – an instance of inspect.Parameter, used as a template for creating a newFParameter:returns: a new instance ofFParameter, usingnativeas a template
-
native¶ A native representation of this
FParameteras aninspect.Parameter, fit for an instance ofinspect.Signature
-
replace(*, kind=<void>, name=<void>, interface_name=<void>, default=<void>, factory=<void>, type=<void>, converter=<void>, validator=<void>, bound=<void>, contextual=<void>, metadata=<void>)¶ An evolution method that generates a new
FParameterderived from this instance and the provided updates.Parameters: Returns: an instance of ~forge.FParameter
Constructors¶
-
forge.pos(name=None, interface_name=None, *, default=<empty>, factory=<empty>, type=<empty>, converter=None, validator=None, bound=False, metadata=None) → forge._signature.FParameter¶ A factory method for creating positional-only
FParameterinstances.Parameters:
-
forge.pok(name=None, interface_name=None, *, default=<empty>, factory=<empty>, type=<empty>, converter=None, validator=None, bound=False, metadata=None) → forge._signature.FParameter¶ A factory method for creating positional-or-keyword
FParameterinstances.Parameters:
-
forge.arg()¶ a convenience for
forge.pok()
-
forge.ctx(name=None, interface_name=None, *, type=<empty>, metadata=None) → forge._signature.FParameter¶ A factory method for creating positional-or-keyword
FParameterinstances that arecontextual(this value is passed to otherFParameter`s ``converter`andvalidatorfunctions.)Parameters:
-
forge.vpo(name, *, type=<empty>, converter=None, validator=None, metadata=None) → forge._signature.FParameter¶ A factory method for creating var-positional
FParameterinstances.Parameters:
-
forge.kwo(name=None, interface_name=None, *, default=<empty>, factory=<empty>, type=<empty>, converter=None, validator=None, bound=False, metadata=None) → forge._signature.FParameter¶ A factory method for creating keyword-only
FParameterinstances.Parameters:
-
forge.kwarg()¶ a convenience for
forge.kwo()
Helpers¶
-
forge.findparam(parameters: Iterable[_T_PARAM], selector: Union[str, typing.Iterable[str], typing.Callable[[~_T_PARAM], bool]]) → Iterator[_T_PARAM]¶ Return an iterator yielding those parameters (of type
inspect.ParameterorFParameter) that are mached by the selector.selectoris used differently based on what is supplied:- str: a parameter is found if its
nameattribute is contained - Iterable[str]: a parameter is found if its
nameattribute is - contained
- Iterable[str]: a parameter is found if its
- callable: a parameter is found if the callable (which receives the
- parameter), returns a truthy value.
Parameters: - parameters¶ – an iterable of
inspect.ParameterorFParameter - selector¶ – an identifier which is used to determine whether a parameter matches.
Returns: an iterator yield parameters
- str: a parameter is found if its
-
forge.args(name: Union[str, NoneType] = None, *, type: Any = <empty>, converter: Union[typing.Callable[[typing.Any, str, typing.Any], typing.Any], typing.Iterable[typing.Callable[[typing.Any, str, typing.Any], typing.Any]], NoneType] = None, validator: Union[typing.Callable[[typing.Any, str, typing.Any], typing.Any], typing.Iterable[typing.Callable[[typing.Any, str, typing.Any], typing.Any]], NoneType] = None, metadata: Union[typing.Mapping, NoneType] = None) → VarPositional¶ A psuedo-sequence that unpacks as a var-positional
FParameter.Can also be called with arguments to generate another instance.
Typical usage:
>>> import forge >>> fsig = forge.FSignature(*forge.args) >>> print(fsig) <FSignature (*args)> >>> import forge >>> fsig = forge.FSignature(*forge.args(name='vars')) >>> print(fsig) <FSignature (*vars)>
While
namecan be supplied (by default it’sargs),interface_nameis unavailable. This is because whenFSignaturemaps parameters, the mapping between var-positional parameters is 1:1, so the interface name for var-positional is auto-discovered.Implements
collections.abc.Iterable, with provided:__iter__. Inherits method:__next__.Parameters: a “ready-to-go” instance of
VarPositional, with the nameargs. Use as*args, or supplyreplace()arguments. For example, to change the name toitems:*args(name='items').
-
forge.kwargs= <forge._signature.VarKeyword object>¶ A psuedo-collection that unpacks as a var-keyword
FParameter.Can also be called with arguments to generate another instance.
Typical usage:
>>> import forge >>> fsig = forge.FSignature(**forge.kwargs) >>> print(fsig) <FSignature (**kwargs)> >>> import forge >>> fsig = forge.FSignature(**forge.kwargs(name='items')) >>> print(fsig) <FSignature (**items)>
While
namecan be supplied (by default it’skwargs),interface_nameis unavailable. This is because whenFSignaturemaps parameters, the mapping between var-keyword parameters is 1:1, so the interface name for var-keyword is auto-discovered.Implements
collections.abc.Mapping, with provided:__getitem__,__iter__and__len__. Inherits methods:__contains__,keys,items,values,get,__eq__and__ne__.Parameters: a “ready-to-go” instance of
VarKeyword, with the namekwargs. Use as**kwargs, or supplyreplace()arguments. For example, to change the name toextras:**kwargs(name='extras').
-
forge.self= <FParameter "self">¶ An immutable representation of a signature parameter that encompasses its public name, its interface name, transformations to be applied, and associated meta-data that defines its behavior in a signature.
Note
This class doesn’t need to be invoked directly. Use one of the constructor methods instead:
pos()for positional-onlyFParameterpok()orarg()for positional-or-keywordFParametervpo()for var-positionalFParameterkwo()orkwarg()for keyword-onlyFParametervkw()for var-keywordFParameter
Parameters: - kind – the parameter kind, which detemrines the position of the parameter in a callable signature.
- name – the public name of the parameter.
For example, in
f(x)->g(y),nameisx. - interface_name – the name of mapped-to the parameter.
For example, in
f(x)->g(y),interface_nameisy. - default – the default value for the parameter.
Cannot be supplied alongside a
factoryargument. For example, to achievef(x=3), specify :code`default=3`. - factory – a function that generates a default for the parameter
Cannot be supplied alongside a
defaultargument. For example, to achievef(x=<Factory now>), specifyfactory=default.now(notice: without parentheses). - type – the type annotation of the parameter.
For example, to achieve
f(x: int),typeisint. - converter – a callable or iterable of callables that receive a
ctxargument, anameargument and avalueargument for transforming inputs. - validator – a callable that receives a
ctxargument, anameargument and avalueargument for validating inputs. - bound – whether the parameter is visible in the signature
(requires
defaultorfactoryif True) - contextual – whether the parameter will be passed to
converterandvalidatorcallables as the context (only the first parameter in aFSignaturecan be contextual) - metadata – optional, extra meta-data that describes the parameter
Variables: - POSITIONAL_ONLY – the positional-only
parameter kind constant
inspect.Parameter.POSITIONAL_ONLY - POSITIONAL_OR_KEYWORD – the positional-or-keyword
parameter kind constant
inspect.Parameter.POSITIONAL_OR_KEYWORD - VAR_POSITIONAL – the var-positional constant
parameter kind constant
inspect.Parameter.VAR_POSITIONAL - KEYWORD_ONLY – the keyword-only constant
parameter kind constant
inspect.Parameter.KEYWORD_ONLY - VAR_KEYWORD – the var-keyword constant
parameter kind constant
inspect.Parameter.VAR_KEYWORD
a “ready-to-go” instance of
FParameteras theselfcontext parameter.
-
forge.cls= <FParameter "cls">¶ An immutable representation of a signature parameter that encompasses its public name, its interface name, transformations to be applied, and associated meta-data that defines its behavior in a signature.
Note
This class doesn’t need to be invoked directly. Use one of the constructor methods instead:
pos()for positional-onlyFParameterpok()orarg()for positional-or-keywordFParametervpo()for var-positionalFParameterkwo()orkwarg()for keyword-onlyFParametervkw()for var-keywordFParameter
Parameters: - kind – the parameter kind, which detemrines the position of the parameter in a callable signature.
- name – the public name of the parameter.
For example, in
f(x)->g(y),nameisx. - interface_name – the name of mapped-to the parameter.
For example, in
f(x)->g(y),interface_nameisy. - default – the default value for the parameter.
Cannot be supplied alongside a
factoryargument. For example, to achievef(x=3), specify :code`default=3`. - factory – a function that generates a default for the parameter
Cannot be supplied alongside a
defaultargument. For example, to achievef(x=<Factory now>), specifyfactory=default.now(notice: without parentheses). - type – the type annotation of the parameter.
For example, to achieve
f(x: int),typeisint. - converter – a callable or iterable of callables that receive a
ctxargument, anameargument and avalueargument for transforming inputs. - validator – a callable that receives a
ctxargument, anameargument and avalueargument for validating inputs. - bound – whether the parameter is visible in the signature
(requires
defaultorfactoryif True) - contextual – whether the parameter will be passed to
converterandvalidatorcallables as the context (only the first parameter in aFSignaturecan be contextual) - metadata – optional, extra meta-data that describes the parameter
Variables: - POSITIONAL_ONLY – the positional-only
parameter kind constant
inspect.Parameter.POSITIONAL_ONLY - POSITIONAL_OR_KEYWORD – the positional-or-keyword
parameter kind constant
inspect.Parameter.POSITIONAL_OR_KEYWORD - VAR_POSITIONAL – the var-positional constant
parameter kind constant
inspect.Parameter.VAR_POSITIONAL - KEYWORD_ONLY – the keyword-only constant
parameter kind constant
inspect.Parameter.KEYWORD_ONLY - VAR_KEYWORD – the var-keyword constant
parameter kind constant
inspect.Parameter.VAR_KEYWORD
a “ready-to-go” instance of
FParameteras theclscontext parameter.
Utils¶
-
forge.callwith(to_: Callable[..., Any], named: Union[typing.Dict[str, typing.Any], NoneType] = None, unnamed: Union[typing.Iterable, NoneType] = None) → Any¶ Calls and returns the result of
to_with the suppliednamedandunnamedarguments.The arguments and their order as supplied to
to_is determined by iterating over thenamedarguments and assinging the values to the parameters with the key as a name.unnamedarguments are assigned to the var-positional parameter.Usage:
import forge def func(a, b=2, *args, c, d=5, **kwargs): return (a, b, args, c, d, kwargs) assert forge.callwith( func, named=dict(a=1, c=4, e=6), unnamed=(3,), ) == (1, 2, (3,), 4, 5, {'e': 6})
Parameters: - to_¶ – a callable to call with the named and unnamed parameters
- named¶ – a mapping of parameter names to argument values.
Appropriate values are all positional-only,
positional-or-keyword, and keyword-only arguments,
as well as additional var-keyword mapped arguments which will
be used to construct the var-positional argument on
to_(if it has such an argument). Parameters onto_with default values can be ommitted (as expected). - unnamed¶ – an iterable to be passed as the var-positional
parameter. Requires
to_to accept var-positional arguments.
-
forge.repr_callable(callable: Callable) → str¶ Build a string representation of a callable, including the callable’s :attr:
__name__, itsinspect.Parameter`s and its ``return type`usage:
>>> repr_callable(repr_callable) 'repr_callable(callable: Callable) -> str'
Parameters: callable¶ – a Python callable to build a string representation of Returns: the string representation of the function