randog.factory package
- class randog.factory.DictItem(factory: Factory)
- class randog.factory.DictItem(factory: Factory, prop_exists: float)
- class randog.factory.DictItem(item: Tuple[Factory, float])
Bases:
object
A rule for generating values corresponding to a key in the random generation of dict.
- prop_exists: float
probability of key generation
- class randog.factory.Factory
Bases:
ABC
,Generic
[T
]- infinity_iter(*, regenerate: float = 0.0, raise_on_factory_stopped: bool = False, rnd: Random | None = None) Iterator[T]
Returns an infinity iterator which serves result randomly.
The result is INFINITY so do NOT use it directly with for, list, and so on.
However, if the argument raise_on_factory_stopped is not True, the iterator will be stopped if the factory is stopped.
Examples
>>> import randog >>> factory = randog.factory.randstr(length=5) >>> >>> keys = ["foo", "bar"] >>> for k, v in zip(keys, factory.infinity_iter()): ... assert k in keys ... assert isinstance(v, str)
- Parameters:
regenerate (float, default=0.0) – the probability that the original factory generation value is not returned as is, but is regenerated. It affects cases where the original factory returns a value that is not completely random.
raise_on_factory_stopped (bool, default=False) – If True, the iteration raises FactoryStopException in case the factory cannot generate value due to StopIteration. If False, the iteration simply stops in the case.
rnd (Random, optional) – random number generator to be used
- Returns:
An infinity iterator
- Return type:
Iterator[T]
- iter(size: int, *, regenerate: float = 0.0, discard: float = 0.0, raise_on_factory_stopped: bool = False, rnd: Random | None = None) Iterator[T]
Returns an iterator which serves result randomly size times.
Examples
>>> import randog >>> factory = randog.factory.randstr(length=5) >>> >>> for result in factory.iter(10): ... assert isinstance(result, str) >>> >>> results = list(factory.iter(5)) >>> assert len(results) == 5
- Parameters:
size (int) – the number of the iterator. However, if the argument raise_on_factory_stopped is not True, fewer iterations than the specified size will be executed if the factory is stopped. Also, if the argument discard is specified, the size may be less.
regenerate (float, default=0.0) – the probability that the original factory generation value is not returned as is, but is regenerated. It affects cases where the original factory returns a value that is not completely random.
discard (float, default=0.0) – the probability that the original factory generation value is not returned as is, but is discarded. If discarded, the number of times the value is generated is less than size.
raise_on_factory_stopped (bool, default=False) – If True, the iteration raises FactoryStopException in case the factory cannot generate value due to StopIteration. If False, the iteration simply stops in the case.
rnd (Random, optional) – random number generator to be used
- Returns:
An iterator
- Return type:
Iterator[T]
- next(*, raise_on_factory_stopped: bool = False) T
Generate a value randomly according to the rules specified when assembling the factory.
- Parameters:
raise_on_factory_stopped (bool, default=False) – If True, raises FactoryStopException in case the factory cannot generate value due to StopIteration. If False, simply raises StopIteration.
- Returns:
a value generated randomly
- Return type:
T
- or_none(prob: float = 0.1, *, lazy_choice: bool = False, rnd: Random | None = None) Factory[T | None]
Returns a factory whose result may be None with the specified probability.
Examples
>>> import randog >>> >>> factory = randog.factory.randstr().or_none(0.2) >>> >>> generated = factory.next() >>> assert generated is None or isinstance(generated, str)
- Parameters:
prob (float, default=0.1) – Probability that the result is None
lazy_choice (bool, optional) – If it is True, when generating a value, first generate value with the base factory and then decides whether to adopt it or None. Otherwise, it first decides whether to return None or generate a value and return it, and then generates a value only if it is returned.
rnd (Random, optional) – random number generator to be used
- Returns:
A factory whose result may be None with the specified probability.
- Return type:
Factory[T|None]
- post_process(post_process: Callable[[T], R]) Factory[R]
Returns a factory whose result will be modified by post_process
Examples
>>> import randog >>> >>> # use post_process to format the random decimal value >>> factory = ( ... randog.factory.randdecimal(0, 50000, decimal_len=2) ... .post_process(lambda x: f"${x:,}") ... ) >>> >>> # examples: '$12,345.67', '$3,153.21', '$12.90', etc. >>> generated = factory.next() >>> assert isinstance(generated, str) >>> assert generated[0] == "$"
- Parameters:
post_process (Callable[[T], R]) – the mapping to modify the result
- Returns:
A factory whose result will be modified by post_process.
- Return type:
Factory[R]
- post_process_items(default_process: Callable[[Any], Any] | None = None, **processes: Callable[[Any], Any]) Factory[R]
Returns a factory whose result will be dict whose items is modified by processes
Examples
>>> import randog >>> >>> # use post_process_items to format the random decimal value '["count"]' >>> factory = ( ... randog.factory.randdict( ... name=randog.factory.randstr(), ... count=randog.factory.randdecimal(0, 50000, decimal_len=2), ... ).post_process_items(count=lambda x: f"${x:,}") ... ) >>> >>> # examples: {'name': 'sir1w94s', 'count': '$12,345.67'}, etc. >>> generated = factory.next() >>> assert isinstance(generated["count"], str) >>> assert generated["count"][0] == "$"
- Parameters:
default_process (Callable[[Any], Any] | None) – the mapping to modify items which is not defined in processes
processes (Callable[[Any], Any]) – functions to modify each item
- Returns:
A factory whose result will be dict whose items is modified by processes
- Return type:
Factory[R]
- class randog.factory.FactoryDef(factory: randog.factory._base.Factory, csv_columns: Sequence[str | Callable[[Mapping], Any]] | None, output_linesep: randog._utils.linesep.Linesep | None, output_encoding: str | None)
Bases:
object
- csv_columns: Sequence[str | Callable[[Mapping], Any]] | None
- output_encoding: str | None
- output_linesep: Linesep | None
- exception randog.factory.FactoryStopException
Bases:
Exception
- class randog.factory.FromExampleContext(path: Tuple[Any, ...], custom_func: _CustomFunc | Sequence[_CustomFunc] | None, rnd: Random | None, examples_stack: Tuple[Any, ...], custom_chain_length: int = 0, warned_too_long_custom_chain: bool = False)
Bases:
object
- property current_example: Any
- property custom_chain_length: int
- property custom_funcs: Sequence[_CustomFunc]
- property examples: Tuple[Any, ...]
- property path: Tuple[Any, ...]
- property rnd: Random | None
- set_warned_too_long_custom_chain()
- property signal_terminate_custom: bool
- terminate_custom_chain()
- property warned_too_long_custom_chain: bool
- randog.factory.by_callable(func: Callable[[], T]) Factory[T]
Return a factory generating values by specified callable.
- Parameters:
func (() -> T) – the function generating value
- randog.factory.by_iterator(iterator: Iterator[T]) Factory[T]
Return a factory generating values by specified iterator.
- Parameters:
iterator (Iterator[T]) – the iterator generating value
- randog.factory.const(value: Any, rnd: Random | None = None) Factory[Any]
Return a factory which returns the specified value.
- Parameters:
value (Any) – the value
rnd (Random, optional) – It is not normally used, but it can be accepted as an argument to match other Factory construction functions.
- randog.factory.dice(code: str, *, rnd: Random | None = None) Factory[int]
Return a factory generating random int values by total of the dice faces.
- Parameters:
code (str) – dice notation
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified code is invalid.
- randog.factory.from_example(example: Any, *, custom_func: _CustomFunc | Sequence[_CustomFunc] | None = None, rnd: Random | None = None, context: FromExampleContext | None = None) Factory
Returns a factory generating value like specified example or type.
- Parameters:
example (Any) – the type or the example
custom_func (Callable | Sequence[Callable]) – If specified, this function is executed first and its return value is used as a new example. If it returns a factory, it is used as is. If it returns NotImplemented, from_example behaves as if custom_func was not specified. The context is passed to this function. Multiple functions may be specified for custom_func, and if multiple functions are specified, they are executed in sequence until a value other than NotImplemented is returned. This sequence of processing is also used to create factories for child elements of dict and list. It is recommended that custom_func receives **kwargs to allow for more keyword arguments in future updates.
rnd (Random, optional) – random number generator to be used
context (FromExampleContext, optional) – the context of generation. Normally, you should not specify it. If specified, the context property takes precedence over other arguments.
- Raises:
FactoryConstructionError – When the specified example or type is not supported.
- randog.factory.from_pyfile(file: str | PathLike | IO, *, full_response: bool = False, rnd: Random | None = None) FactoryDef | Factory
Returns a factory defined in the specified file.
- Parameters:
file (str | PathLike | IO) – the filename of the factory definition
full_response (bool (default=False)) – If True is specified, the return value is the FactoryDef dataclass, and data other than the factory can be obtained.
rnd (Random, optional) – random number generator to be used
- randog.factory.increment(initial_value: int | None = None, maximum: int | None = None, *, rnd: Random | None = None) Factory[Any]
Return a factory which returns sequential numbers.
- Parameters:
initial_value (int, optional) – the first value
maximum (int, optional) – the maximum value. If the generated value reaches the maximum value, 1 is generated next. If the maximum value is not specified, it is not reset to 1.
rnd (Random, optional) – It is not normally used, but it can be accepted as an argument to match other Factory construction functions.
- Raises:
FactoryConstructionError – if it is not satisfied 1 <= initial_value <= maximum
- randog.factory.iterrange(initial_value: Any | None = None, maximum: Any | None = None, step: Any | None = None, *, cyclic: bool = False, resume_from: Any | None = None, rnd: Random | None = None) Factory[Any]
Return a factory which returns sequential numbers.
This is a factory that generates values that are shifted by the value specified in step from initial_value.
If you specify maximum, it will emit StopIterator when a value that exceeds it is about to be generated. However, if cyclic is True, it will not emit StopIterator, but will restart generating from initial_value.
- Parameters:
initial_value – the first value
maximum (optional) – the maximum value
step (optional) – difference between generated values
cyclic (bool) – If it is True, it does not terminate after generating values up to the maximum. The next value depends on the other arguments; by default initial_value is returned.
resume_from (optional) – If cyclic is True and this value is specified, the value specified here is the next value after maximum.
rnd (Random, optional) – It is not normally used, but it can be accepted as an argument to match other Factory construction functions.
- Raises:
FactoryConstructionError – if there is a contradiction in the argument values
- randog.factory.parse_dice_notation(code: str, *, exception: ~typing.Type[Exception] = <class 'ValueError'>) Tuple[int, int]
- randog.factory.randbool(prop_true: float = 0.5, *, rnd: Random | None = None) Factory[bool]
Return a factory generating random bool values.
- Parameters:
prop_true (float) – the probability of True
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randbytearray(*, length: int | Factory[int] | None = None, rnd: Random | None = None) Factory[bytearray]
Return a factory generating random bytearray values.
- Parameters:
length (int|Factory[int], default=8) – length of generated bytes
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randbytes(*, length: int | Factory[int] | None = None, rnd: Random | None = None) Factory[bytes]
Return a factory generating random bytes values.
- Parameters:
length (int|Factory[int], default=8) – length of generated bytes
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randchoice(*values: Any, weights: Sequence[float] | None = None, rnd: Random | None = None) Factory[Any]
Return a factory choosing one of values.
- Parameters:
values (Any) – the values
weights (Sequence[float], optional) – the probabilities that each value is chosen. The length must equal to the number of values.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – No values are specified.
- randog.factory.randdate(minimum: date | datetime | None = None, maximum: date | datetime | None = None, *, rnd: Random | None = None) Factory[date]
Return a factory generating random date values.
- Parameters:
minimum (date | datetime, optional) – the minimum
maximum (date | datetime, optional) – the maximum
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randdatetime(minimum: datetime | date | None = None, maximum: datetime | date | None = None, *, tzinfo: Literal[False] | None | tzinfo = False, rnd: Random | None = None) Factory[datetime]
Return a factory generating random datetime values.
- Parameters:
minimum (datetime | date, optional) – the minimum
maximum (datetime | date, optional) – the maximum
tzinfo (tzinfo | None, optional) – If specified, the tzinfo of result will be fixed to this value (False means no specification). When it fixes aware datetime to aware, the time is corrected. Otherwise, only the tzinfo is changed.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randdecimal(minimum: SupportsFloat | None = None, maximum: SupportsFloat | None = None, *, decimal_len: int | None = None, p_inf: SupportsFloat = 0.0, n_inf: SupportsFloat = 0.0, nan: SupportsFloat = 0.0, distribution: Literal['uniform', 'exp_uniform'] = 'uniform', rnd: Random | None = None) Factory[Decimal]
Return a factory generating random Decimal values.
- Parameters:
minimum (float, optional) – the minimum
maximum (float, optional) – the maximum
decimal_len (int, optional) – the length of decimal part
p_inf (float, default=0) – the probability of positive infinity
n_inf (float, default=0) – the probability of negative infinity
nan (float, default=0) – the probability of NaN
distribution ("uniform"|"exp_uniform", default="uniform") – probability distribution. If ‘uniform’, the distribution is uniform. If ‘exp_uniform’, the distribution of digits (log with a base of 10) is uniform.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randdict(items_dict: Mapping[Hashable, Factory | Tuple[Factory, float] | DictItem] | None = None, *, rnd: Random | None = None, **items: Factory | Tuple[Factory, float] | DictItem) Factory[dict]
Return a factory generating random dict.
- Parameters:
items (Mapping) – the factories of each key. If items_dict is specified, items will be ignored.
items_dict (Mapping) – the factories of each key. Use when keyword arguments cannot be specified.
rnd (Random, optional) – random number generator to be used
- randog.factory.randenum(enum_cls: Type[Enum], weights: Callable[[Any], float] | None = None, rnd: Random | None = None) Factory[Any]
Return a factory choosing one of specified enum.
- Parameters:
enum_cls (Type[Enum]) – the enum class
weights (Callable[[Enum], float], optional) – the probabilities that each value is chosen.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – No values are specified.
- randog.factory.randfloat(minimum: SupportsFloat | None = None, maximum: SupportsFloat | None = None, *, p_inf: SupportsFloat = 0.0, n_inf: SupportsFloat = 0.0, nan: SupportsFloat = 0.0, distribution: Literal['uniform', 'exp_uniform'] = 'uniform', rnd: Random | None = None) Factory[float]
Return a factory generating random float values.
- Parameters:
minimum (float, optional) – the minimum
maximum (float, optional) – the maximum
p_inf (float, default=0) – the probability of positive infinity
n_inf (float, default=0) – the probability of negative infinity
nan (float, default=0) – the probability of NaN
distribution ("uniform"|"exp_uniform", default="uniform") – probability distribution. If ‘uniform’, the distribution is uniform. If ‘exp_uniform’, the distribution of digits (log with a base of 2) is uniform.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randint(minimum: int, maximum: int, *, distribution: Literal['uniform', 'exp_uniform'] = 'uniform', rnd: Random | None = None) Factory[int]
Return a factory generating random int values.
- Parameters:
minimum (int) – the minimum
maximum (int) – the maximum
distribution ("uniform"|"exp_uniform", default="uniform") – probability distribution. If ‘uniform’, the distribution is uniform. If ‘exp_uniform’, the distribution of digits (log with a base of 2) is uniform.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randipv4(network: IPv4Network | Iterable[IPv4Network] | None = None, *, rnd: Random | None = None) Factory[IPv4Address]
Return a factory generating random int values.
- Parameters:
network (IPv4Network | Iterable[IPv4Network]) – address space that is a candidate for the generated IP address
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randlist(*items: ~randog.factory._base.Factory, length: int | ~randog.factory._base.Factory[int] | None = None, type: ~typing.Callable[[~typing.Iterator[~typing.Any]], ~randog.factory._list.T] = <class 'list'>, rnd: ~random.Random | None = None, items_list: ~typing.Sequence[~randog.factory._base.Factory] | None = None) Factory[list]
Return a factory generating random list.
- Parameters:
items (Factory) – the factories of each item. If items_list is specified, items will be ignored.
length (int|Factory[int], optional) – length of generated list. If not specified, the length of generated list will be equals to the number of items.
type (type, default=list) – the type of generated object
rnd (Random, optional) – random number generator to be used
items_list (Sequence[Factory], optional) – the factories of each item. Use when positional arguments cannot be specified.
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randstr(*, length: int | Factory[int] | None = None, charset: str | None = None, regex: str | None = None, rnd: Random | None = None) Factory[str]
Return a factory generating random str values.
- Parameters:
length (int|Factory[int], default=8) – length of generated string
charset (str, optional) – characters to be used
regex (str, optional) – regular expression for generated string. It cannot be used with length or charset.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randtime(minimum: time | None = None, maximum: time | None = None, *, tzinfo: Literal[False] | None | tzinfo = False, rnd: Random | None = None) Factory[time]
Return a factory generating random time values.
- Parameters:
minimum (time, optional) – the minimum
maximum (time, optional) – the maximum
tzinfo (tzinfo | None, optional) – If specified, the tzinfo of result will be fixed to this value (False means no specification). When it fixes aware datetime to aware, the time is corrected. Otherwise, only the tzinfo is changed.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.randtimedelta(minimum: timedelta | None = None, maximum: timedelta | None = None, *, unit: timedelta | None = None, rnd: Random | None = None) Factory[timedelta]
Return a factory generating random timedelta values.
- Parameters:
minimum (timedelta, optional) – the minimum
maximum (timedelta, optional) – the maximum
unit (timedelta, optional) – the atomic unit
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – When the specified generating conditions are inconsistent.
- randog.factory.union(*factories: Factory, weights: Sequence[float] | None = None, lazy_choice: bool = False, rnd: Random | None = None) Factory[Any]
Return a factory generating value by one of specified factories.
- Parameters:
factories (Factory) – the factories
weights (Sequence[float], optional) – the probabilities that each factory is chosen. The length must equal to the number of factories.
lazy_choice (bool, optional) – If it is True, when generating a value, first generate values with all factories and then decide which of them to adopt. Otherwise, it first decides which factory to adopt, and then generates a value using only that factory.
rnd (Random, optional) – random number generator to be used
- Raises:
FactoryConstructionError – No factories are specified.