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
forge
exceptions
-
class
forge.
ImmutableInstanceError
¶ An error that is raised when trying to set an attribute on a
Immutable
instance.
Marker¶
-
class
forge.
empty
¶ A simple
MarkerMeta
class useful for denoting that no input was suplied. Used in place ofinspect.Parameter.empty
as 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-
empty
value.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.empty
value.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
MarkerMeta
class 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]) → None¶ An immutable data structure that provides the recipe for mapping an
FSignature
to an underlying callable.Parameters: - fsignature¶ – an instance of
FSignature
that provides the public and private interface. - callable¶ – a callable that ultimately receives the arguments provided
to public
FSignature
interface.
Variables: - callable – see
callable
- fsignature – see
fsignature
- parameter_map – a
types.MappingProxy
that exposes the strategy of how to map from theMapper.fsignature
to 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
FSignature
to map from - to_¶ – the
inspect.Signature
to map to
Returns: a
types.MappingProxyType
that 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
FSignature
instances directly by providing anFSignature
torevise()
:import forge in_ = forge.FSignature() out_ = forge.Revision().revise(in_) assert in_ == out_
The
revise()
method is expected to return an instance ofFSignature
that is not validated. This can be achieved by supplying__validate_attributes__=False
to eitherFSignature
orreplace()
.Instances of
Revision
don’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:
previous
is 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 FSignature
to modifyReturns: a modified instance of FSignature
-
Group revisions¶
-
class
forge.
compose
(*revisions)¶ Batch revision that takes
Revision
instances and applies theirrevise()
usingfunctools.reduce()
.Parameters: revisions¶ – instances of Revision
, used to revise theFSignature
.-
revise
(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Applies
revisions
No 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 FSignature
to 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) → None¶ The
copy
revision 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
FParameter
and returns a truthy value whether to include it. - exclude¶ – a string, iterable of strings, or a function that receives
an instance of
FParameter
and returns a truthy value whether to exclude it.
Raises: TypeError – if
include
andexclude
are 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 byinclude
andexclude
.Unlike most subclasses of
Revision
, validation is performed on the updatedFSignature
. This is becausecopy
takes a callable which is required by Python to have a valid signature, so it’s impossible to return an invalid signature.Parameters: previous¶ – the FSignature
to modifyReturns: a modified instance of FSignature
-
class
forge.
manage
(callable: Callable[forge._signature.FSignature, forge._signature.FSignature]) → None¶ Revision that revises a
FSignature
with 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
callable
for revision.Warning
No validation is typically performed in the
revise
method. Consider providing False as an argument value to__validate_parameters__
, so that this revision can be used within the context of acompose
revision.Parameters: previous¶ – the FSignature
to modifyReturns: a modified instance of FSignature
-
-
class
forge.
returns
(type: Any = <empty>) → None¶ The
returns
revision updates a signature’sreturn-type
annotation.import forge @forge.returns(int) def x(): pass assert forge.repr_callable(x) == "x() -> int"
Parameters: type¶ – the return type
for the factoryVariables: return_annotation – the return type
used 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 type
annoation is set without wrapping the function. Otherwise, the__mapper__
and__signature__
are updatedParameters: callable¶ – see callable
Returns: 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 FSignature
to modifyReturns: a modified instance of FSignature
-
-
class
forge.
synthesize
(*parameters, **named_parameters)¶ Revision that builds a new signature from instances of
FParameter
Order parameters with the following strategy:
- arguments are returned in order
- keyword arguments are sorted by
_creation_order
, and evolved with thekeyword
value 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.7
don’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¶ –
FParameter
instances to be ordered - named_parameters¶ –
FParameter
instances 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
parameters
andnamed_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 FSignature
to 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) → 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 FSignature
to 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) → None¶ 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
FParameter
and 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
selector
matches no parameters
-
revise
(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Deletes one or more parameters from
previous
based 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 FSignature
to 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) → 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
FParameter
and 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
FParameter
and returns a truthy value whether to place the provided parameter before it.
-
revise
(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Inserts the
insertion
into 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 FSignature
to 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>) → None¶ 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
FParameter
and 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
selector
matches 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 FSignature
to 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) → None¶ 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
FParameter
and returns a truthy value whether to place the provided parameter before it. - parameter¶ – an instance of
FParameter
to 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 FSignature
to 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
FParameter
and 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
FParameter
and 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
FParameter
and returns a truthy value whether to place the provided parameter before it.
-
revise
(previous: forge._signature.FSignature) → forge._signature.FSignature¶ Translocates (moves) the
parameter
into 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 FSignature
to 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) → None¶ An immutable, validated representation of a signature composed of
FParameter
instances, 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
FParameter
that 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
FSignature
from a callable. Calls down tofrom_native()
to do the heavy loading.Parameters: callable¶ – a callable from which to derive the FSignature
Returns: an instance of FSignature
derived from thecallable
argument.
-
classmethod
from_native
(signature: inspect.Signature) → forge._signature.FSignature¶ A factory method that creates an instance of
FSignature
from an instance ofinspect.Signature
. Calls down toFParameter
to map theinspect.Signature.parameters
toinspect.Parameter
instances.The
return type
annotation from the provided signature is not retained, asfrom_native()
doesn’t provide this functionality.Parameters: signature¶ – an instance of inspect.Signature
from which to derive theFSignature
Returns: an instance of FSignature
derived from thesignature
argument.
-
native
¶ Provides a representation of this
FSignature
as 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
FSignature
with replaced attributes.Parameters: - parameters¶ – see
parameters
- return_annotation¶ – see
return_annotation
- __validate_parameters__¶ – see
__validate_parameters__
Returns: a new copy of
FSignature
revised 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
context
parameter, and that it is the first parameter (if it is provided.)
- that at most there is one
- that no two instances of
FParameter
share the same name
orinterface_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) → 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-onlyFParameter
pok()
orarg()
for positional-or-keywordFParameter
vpo()
for var-positionalFParameter
kwo()
orkwarg()
for keyword-onlyFParameter
vkw()
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)
,name
isx
. - interface_name¶ – the name of mapped-to the parameter.
For example, in
f(x)
->g(y)
,interface_name
isy
. - default¶ – the default value for the parameter.
Cannot be supplied alongside a
factory
argument. 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
default
argument. 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)
,type
isint
. - converter¶ – a callable or iterable of callables that receive a
ctx
argument, aname
argument and avalue
argument for transforming inputs. - validator¶ – a callable that receives a
ctx
argument, aname
argument and avalue
argument for validating inputs. - bound¶ – whether the parameter is visible in the signature
(requires
default
orfactory
if True) - contextual¶ – whether the parameter will be passed to
converter
andvalidator
callables as the context (only the first parameter in aFSignature
can 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
FParameter
instances that arecontextual
(this value is passed to otherFParameter`s ``converter`
andvalidator
functions.)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
FParameter
instances.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
FParameter
instances.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
FParameter
instances.Parameters:
-
classmethod
create_var_keyword
(name, *, type=<empty>, converter=None, validator=None, metadata=None) → forge._signature.FParameter¶ A factory method for creating var-keyword
FParameter
instances.Parameters:
-
classmethod
create_var_positional
(name, *, type=<empty>, converter=None, validator=None, metadata=None) → forge._signature.FParameter¶ A factory method for creating var-positional
FParameter
instances.Parameters:
-
class
empty
¶ A simple
MarkerMeta
class useful for denoting that no input was suplied. Used in place ofinspect.Parameter.empty
as 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-
empty
value.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.empty
value.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
FParameter
instances frominspect.Parameter
instances.Parameter descriptions are a subset of those defined on
FParameter
Parameters: native¶ – an instance of inspect.Parameter
, used as a template for creating a newFParameter
:returns: a new instance ofFParameter
, usingnative
as a template
-
native
¶ A native representation of this
FParameter
as 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
FParameter
derived 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
FParameter
instances.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
FParameter
instances.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
FParameter
instances that arecontextual
(this value is passed to otherFParameter`s ``converter`
andvalidator
functions.)Parameters:
-
forge.
vpo
(name, *, type=<empty>, converter=None, validator=None, metadata=None) → forge._signature.FParameter¶ A factory method for creating var-positional
FParameter
instances.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
FParameter
instances.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.Parameter
orFParameter
) that are mached by the selector.selector
is used differently based on what is supplied:- str: a parameter is found if its
name
attribute is contained - Iterable[str]: a parameter is found if its
name
attribute 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.Parameter
orFParameter
- 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
name
can be supplied (by default it’sargs
),interface_name
is unavailable. This is because whenFSignature
maps 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
name
can be supplied (by default it’skwargs
),interface_name
is unavailable. This is because whenFSignature
maps 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-onlyFParameter
pok()
orarg()
for positional-or-keywordFParameter
vpo()
for var-positionalFParameter
kwo()
orkwarg()
for keyword-onlyFParameter
vkw()
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)
,name
isx
. - interface_name – the name of mapped-to the parameter.
For example, in
f(x)
->g(y)
,interface_name
isy
. - default – the default value for the parameter.
Cannot be supplied alongside a
factory
argument. 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
default
argument. 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)
,type
isint
. - converter – a callable or iterable of callables that receive a
ctx
argument, aname
argument and avalue
argument for transforming inputs. - validator – a callable that receives a
ctx
argument, aname
argument and avalue
argument for validating inputs. - bound – whether the parameter is visible in the signature
(requires
default
orfactory
if True) - contextual – whether the parameter will be passed to
converter
andvalidator
callables as the context (only the first parameter in aFSignature
can 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
FParameter
as theself
context 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-onlyFParameter
pok()
orarg()
for positional-or-keywordFParameter
vpo()
for var-positionalFParameter
kwo()
orkwarg()
for keyword-onlyFParameter
vkw()
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)
,name
isx
. - interface_name – the name of mapped-to the parameter.
For example, in
f(x)
->g(y)
,interface_name
isy
. - default – the default value for the parameter.
Cannot be supplied alongside a
factory
argument. 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
default
argument. 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)
,type
isint
. - converter – a callable or iterable of callables that receive a
ctx
argument, aname
argument and avalue
argument for transforming inputs. - validator – a callable that receives a
ctx
argument, aname
argument and avalue
argument for validating inputs. - bound – whether the parameter is visible in the signature
(requires
default
orfactory
if True) - contextual – whether the parameter will be passed to
converter
andvalidator
callables as the context (only the first parameter in aFSignature
can 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
FParameter
as thecls
context 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 suppliednamed
andunnamed
arguments.The arguments and their order as supplied to
to_
is determined by iterating over thenamed
arguments and assinging the values to the parameters with the key as a name.unnamed
arguments 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