fake module

https://github.com/barseghyanartur/fake.py/

class fake.AuthorshipData[source]

Bases: object

first_names: Set[str] = {'Andre', 'Andrew', 'Andrey', 'Anthony', 'Barry', 'Ben', 'Benjamin', 'Christian', 'Collin', 'David', 'Donald', 'Eric', 'Ezio', 'George', 'Gregor', 'Guido', 'Guilherme', 'Jack', 'Jacques', 'Jiwon', 'Ka-Ping', 'Keith', 'Kenneth', 'Lars', 'Marc-Andre', 'Martin', 'Michael', 'Mike', 'Nadeem', 'Nick', 'Paul', 'Piers', 'Skip', 'Steen', 'Steven', 'Thomas', 'Victor', 'Vinay', 'Zooko'}
last_names: Set[str] = {'Ascher', 'Baxter', 'Bland', 'Boutsioukis', 'Dalke', 'Dart', 'Diederich', 'Dragon De Monsyne', 'Edds', 'Felt', 'Frechet', 'Gertzfield', 'Gust', 'Heimes', 'J', 'Kippes', 'Larson', 'Lauder', 'Lemburg', 'Lingl', 'Lumholt', 'Melotti', 'Montanaro', "O'Whielacronx", 'Peterson', 'Petrov', 'Polo', 'Reitz', 'Roberge', 'Sajip', 'Seo', 'Stinner', 'Stufft and individual contributors', 'Vawda', 'Warsaw', 'Winter', 'Wouters', 'Yee', 'van Rossum', 'von Loewis'}
class fake.BaseStorage(*args, **kwargs)[source]

Bases: object

Base storage.

abstract abspath(filename: Any) str[source]

Return absolute path.

abstract exists(filename: Any) bool[source]

Check if file exists.

generate_basename(prefix: str = 'tmp', length: int = 8) str[source]

Generate a random alphanumeric sequence.

abstract generate_filename(extension: str, prefix: Optional[str] = None, basename: Optional[str] = None) Any[source]

Generate filename.

abstract relpath(filename: Any) str[source]

Return relative path.

Delete the file.

abstract write_bytes(filename: Any, data: bytes) int[source]

Write bytes.

abstract write_text(filename: Any, data: str, encoding: Optional[str] = None) int[source]

Write text.

class fake.CLI(faker: Optional[Faker] = None)[source]

Bases: object

execute_command() None[source]
setup_parser() ArgumentParser[source]
class fake.DjangoModelFactory(**kwargs)[source]

Bases: ModelFactory

Django ModelFactory.

classmethod create(**kwargs)[source]
classmethod save(instance)[source]

Save the instance.

class fake.DocxGenerator(faker: Faker)[source]

Bases: object

DocxGenerator - generates a DOCX file with text.

Usage example:

from pathlib import Path
from fake import FAKER

Path("/tmp/example.docx").write_bytes(
    DocxGenerator(FAKER).create(nb_pages=100)
)
create(nb_pages: Optional[int] = None, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None) bytes[source]
class fake.Factory(faker: Optional[Faker] = None)[source]

Bases: object

Factory.

property faker
class fake.FactoryMethod(method_name: str, faker: Optional[Faker] = None, **kwargs)[source]

Bases: object

class fake.Faker(alias: Optional[str] = None)[source]

Bases: object

fake.py - simplified, standalone alternative with no dependencies.


Usage example:

from fake import FAKER

print(FAKER.first_name())  # Random first name
print(FAKER.last_name())  # Random last name
print(FAKER.name())  # Random name
print(FAKER.word())  # Random word from the Zen of Python
print(FAKER.words(nb=3))  # List of 3 random words from Zen of Python
print(FAKER.sentence())  # Random sentence (5 random words by default)
print(FAKER.paragraph())  # Paragraph (5 random sentences by default)
print(FAKER.paragraphs())  # 3 random paragraphs
print(FAKER.text())  # Random text up to 200 characters
print(FAKER.file_name())  # Random filename with '.txt' extension
print(FAKER.email())  # Random email
print(FAKER.url())  # Random URL
print(FAKER.pyint())  # Random integer
print(FAKER.pybool())  # Random boolean
print(FAKER.pystr())  # Random string
print(FAKER.pyfloat())  # Random float

PDF:

from pathlib import Path
from fake import FAKER, TextPdfGenerator, GraphicPdfGenerator

Path("/tmp/graphic_pdf.pdf").write_bytes(
    FAKER.pdf(nb_pages=100, generator=GraphicPdfGenerator)
)

Path("/tmp/text_pdf.pdf").write_bytes(
    FAKER.pdf(nb_pages=100, generator=TextPdfGenerator)
)

Various image formats:

from pathlib import Path
from fake import FAKER

Path("/tmp/image.png").write_bytes(FAKER.png())

Path("/tmp/image.svg").write_bytes(FAKER.svg())

Path("/tmp/image.bmp").write_bytes(FAKER.bmp())

Path("/tmp/image.gif").write_bytes(FAKER.gif())

Note, that all image formats accept size (default: (100, 100)) and color`(default: `(255, 0, 0)) arguments.

bin(length: int = 16) bytes[source]

Create random bytes.

bin_file(length: int = 16, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, **kwargs) StringValue[source]

Create a BIN file.

bmp(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255)) bytes[source]

Create a BMP image of a specified size and colour.

Parameters:
  • size – Tuple of width and height of the image in pixels.

  • color – Colour of the image in RGB format (tuple of three integers).

Returns:

Byte content of the BMP image.

Return type:

bytes

bmp_file(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, extension: Optional[str] = None) StringValue[source]

Create a BMP image file of a specified size and colour.

bothify(value: str, letters: str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', digits: str = '0123456789') str

Randomise string: ? is replaced with letter, # with number.

city() str[source]

Get a random city.

company_email(domain_names: Optional[Tuple[str, ...]] = None) str[source]

Generate a random company email.

country() str[source]

Get a random country.

country_code() str[source]

Get a random country code.

date(start_date: str = '-7d', end_date: str = '+0d', tzinfo: timezone = datetime.timezone.utc) date[source]

Generate random date between start_date and end_date.

Parameters:
  • start_date – The start date from which the random date should be generated in the shorthand notation.

  • end_date – The end date up to which the random date should be generated in the shorthand notation.

  • tzinfo – The timezone.

Returns:

A string representing the formatted date.

Return type:

date

date_time(start_date: str = '-7d', end_date: str = '+0d', tzinfo: timezone = datetime.timezone.utc) datetime[source]

Generate a random datetime between start_date and end_date.

Parameters:
  • start_date – The start datetime from which the random datetime should be generated in the shorthand notation.

  • end_date – The end datetime up to which the random datetime should be generated in the shorthand notation.

  • tzinfo – The timezone.

Returns:

A string representing the formatted datetime.

Return type:

datetime

dir_path(depth: int = 1) str[source]

Generate a random dir path.

docx(nb_pages: Optional[int] = 1, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None) bytes[source]

Create a DOCX document.

docx_file(nb_pages: int = 1, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None) StringValue[source]

Create a DOCX document file.

domain_name(tlds: Optional[Tuple[str, ...]] = None) str[source]

Generate a random domain name.

email(domain_names: Optional[Tuple[str, ...]] = None) str[source]

Generate a random email.

eml(options: Optional[Dict[str, Any]] = None, content: Optional[str] = None, subject: Optional[str] = None, **kwargs) BytesValue[source]

Generate an EML file bytes.

Parameters:
  • options – Options (non-structured) for complex types, such as ZIP.

  • content – Email body text.

  • subject – Email subject.

  • **kwargs

    Additional keyword arguments to pass to the function.

Return type:

BytesValue

Returns:

Relative path (from root directory) of the generated file or raw content of the file.

Usage example. A complex case.

from fake import create_inner_docx_file, FAKER

eml_file = FAKER.eml_file(
    prefix="zzz_email_",
    options={
        "count": 5,
        "create_inner_file_func": create_inner_docx_file,
        "create_inner_file_args": {
            "prefix": "zzz_file_",
        },
    }
)
eml_file(metadata: Optional[MetaData] = None, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, options: Optional[Dict[str, Any]] = None, content: Optional[str] = None, subject: Optional[str] = None, **kwargs) StringValue[source]

Create an EML file.

file_extension() str[source]

Generate a random extension.

file_name(prefix: Optional[str] = '', extension: str = 'txt') str[source]

Generate a random filename.

file_path(prefix: Optional[str] = '', extension: str = 'txt') str[source]

Generate a random file path.

first_name() str[source]

Generate a first name.

first_names(nb: int = 5) List[str][source]

Generate a list of first names.

free_email(domain_names: Optional[Tuple[str, ...]] = None) str[source]

Generate a random free email.

free_email_domain() str[source]

Generate a random free email domain.

generic_file(content: Union[bytes, str], extension: str, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None) StringValue[source]

Create a generic file.

geo_location() str[source]

Get a random geo-location.

static get_by_alias(alias: str) Optional[Faker][source]
static get_by_uid(uid: str) Optional[Faker][source]
gif(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255)) bytes[source]

Create a GIF image of a specified size and colour.

Parameters:
  • size – Tuple of width and height of the image in pixels.

  • color – Colour of the image in RGB format (tuple of three integers).

Returns:

Byte content of the GIF image.

Return type:

bytes

gif_file(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, extension: Optional[str] = None) StringValue[source]

Create a GIF image file of a specified size and colour.

iban(country_code: Optional[str] = None, bank_length: int = 8, account_length: int = 10) str[source]

Generate a random valid IBAN number.

image(image_format: Literal['png', 'svg', 'bmp', 'gif', 'tif', 'ppm', 'jpg'] = 'png', size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255)) bytes[source]

Create an image of a specified format, size and colour.

image_url(width: int = 800, height: int = 600, service_url: Optional[str] = None) str[source]

Generate a random image URL.

ipv4() str[source]

Generate a random IP v4.

isbn10()[source]

Generate a random valid ISBN-10.

isbn13() str[source]

Generate a random valid ISBN-13, starting with 978 or 979.

jpg(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (128, 128, 128)) bytes[source]

Create a JPG image of a specified size and colour.

Parameters:
  • size – Tuple of width and height of the image in pixels.

  • color – Colour of the image in RGB format, tuple of three integers: (0-255, 0-255, 0-255).

Returns:

Byte content of the JPG image.

Return type:

bytes

jpg_file(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (128, 128, 128), storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, extension: Optional[str] = None) StringValue[source]

Create a JPG image file of a specified size and colour.

last_name() str[source]

Generate a last name.

last_names(nb: int = 5) List[str][source]

Generate a list of last names.

lat() float

Generate a random latitude.

latitude() float[source]

Generate a random latitude.

latitude_longitude() Tuple[float, float][source]

Generate a random (latitude, longitude) pair.

latlng() Tuple[float, float]

Generate a random (latitude, longitude) pair.

latlon() Tuple[float, float]

Generate a random (latitude, longitude) pair.

lazy_string_template(template: str, wrap_chars_after: Optional[int] = None, faker: Optional[Faker] = None) LazyStringTemplate[source]

Lazy string template.

lng() float

Generate a random longitude.

load_data()[source]
load_geo_locations() None[source]
load_locales_and_country_codes() None[source]
load_names() None[source]
load_words() None[source]
locale() str[source]

Get a random locale.

lon() float

Generate a random longitude.

longitude() float[source]

Generate a random longitude.

mime_type() str[source]

Generate a random mime type.

name() str[source]

Generate a name.

names(nb: int = 5) List[str][source]

Generate a list of names.

odt(nb_pages: Optional[int] = 1, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None) bytes[source]

Create a ODT document.

odt_file(nb_pages: int = 1, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None) StringValue[source]

Create a ODT document file.

paragraph(nb_sentences: int = 5) str[source]

Generate a paragraph.

paragraphs(nb: int = 3) List[str][source]

Generate a list of paragraphs.

password(length: int = 10, min_lower: int = 1, min_upper: int = 1, min_digits: int = 3, min_special: int = 0) str[source]

Generate a random password.

Parameters:
  • length – Total length of the password. Default is 10.

  • min_lower – Minimum number of lowercase letters. Default is 1.

  • min_upper – Minimum number of uppercase letters. Default is 1.

  • min_digits – Minimum number of digits. Default is 3.

  • min_special – Minimum number of special characters. Default is 0.

Return type:

str

Returns:

Random password string.

Raises:

ValueError

pdf(nb_pages: int = 1, generator: ~typing.Union[~typing.Type[~fake.TextPdfGenerator], ~typing.Type[~fake.GraphicPdfGenerator]] = <class 'fake.GraphicPdfGenerator'>, metadata: ~typing.Optional[~fake.MetaData] = None, **kwargs) bytes[source]

Create a PDF document of a given size.

pdf_file(nb_pages: int = 1, generator: ~typing.Union[~typing.Type[~fake.TextPdfGenerator], ~typing.Type[~fake.GraphicPdfGenerator]] = <class 'fake.GraphicPdfGenerator'>, metadata: ~typing.Optional[~fake.MetaData] = None, storage: ~typing.Optional[~fake.BaseStorage] = None, basename: ~typing.Optional[str] = None, prefix: ~typing.Optional[str] = None, **kwargs) StringValue[source]

Create a PDF file.

png(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255)) bytes[source]

Create a PNG image of a specified size and colour.

Parameters:
  • size – Tuple of width and height of the image in pixels.

  • color – Colour of the image in RGB format (tuple of three integers).

Returns:

Byte content of the PNG image.

Return type:

bytes

png_file(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, extension: Optional[str] = None) StringValue[source]

Create a PNG image file of a specified size and colour.

ppm(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255)) bytes[source]

Create a PPM image of a specified size and colour.

Parameters:
  • size – Tuple of width and height of the image in pixels.

  • color – Colour of the image in RGB format, tuple of three integers: (0-255, 0-255, 0-255).

Returns:

Byte content of the PPM image.

Return type:

bytes

ppm_file(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, extension: Optional[str] = None) StringValue[source]

Create a PPM image file of a specified size and colour.

pybool() bool[source]

Generate a random boolean.

pydecimal(left_digits: int = 5, right_digits: int = 2, positive: bool = True) Decimal[source]

Generate a random Decimal number.

Parameters:
  • left_digits – Number of digits to the left of the decimal point.

  • right_digits – Number of digits to the right of the decimal point.

  • positive – If True, the number will be positive, otherwise it can be negative.

Returns:

Random Decimal number.

Return type:

Decimal

Raises:

ValueError

pyfloat(min_value: float = 0.0, max_value: float = 10.0) float[source]

Generate a random float number.

pyint(min_value: int = 0, max_value: int = 9999) int[source]

Generate a random integer.

Parameters:
  • min_value – Min value of the generated integer. Default is 0.

  • max_value – Max value of the generated integer. Default is 9999.

Return type:

int

Returns:

Random integer within the range [min_value, max_value].

pystr(nb_chars: int = 20) str[source]

Generate a random string.

Parameters:

nb_chars – Number of characters to generate.

Return type:

str

Returns:

Random string.

random_choice(elements: Sequence[T]) T[source]

Random choice: pick a single element from the given list.

random_element(elements: Sequence[T]) T

Random choice: pick a single element from the given list.

random_elements(elements: Sequence[T], length: int) List[T]

Random sample: pick random length elements from the given list.

random_sample(elements: Sequence[T], length: int) List[T][source]

Random sample: pick random length elements from the given list.

randomise_string(value: str, letters: str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', digits: str = '0123456789') str[source]

Randomise string: ? is replaced with letter, # with number.

randomize_string(value: str, letters: str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', digits: str = '0123456789') str

Randomise string: ? is replaced with letter, # with number.

sentence(nb_words: int = 5, suffix: str = '.') str[source]

Generate a sentence.

sentences(nb: int = 3) List[str][source]

Generate a list of sentences.

slug() str[source]

Generate a slug.

slugs(nb: int = 5) List[str][source]

Generate a list of slugs.

string_template(template: str, wrap_chars_after: Optional[int] = None, faker: Optional[Faker] = None) str[source]

String template.

svg(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255)) bytes[source]

Create an SVG image of a specified size and colour.

Parameters:
  • size – Tuple of width and height of the image in pixels.

  • color – Colour of the image in RGB format (tuple of three integers).

Returns:

Byte content of the SVG image.

Return type:

bytes

svg_file(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, extension: Optional[str] = None) StringValue[source]

Create an SVG image file of a specified size and colour.

tar(options: Optional[Dict[str, Any]] = None, compression: Optional[Literal['gz', 'bz2', 'xz']] = None, **kwargs) BytesValue[source]

Generate a TAR archive file as bytes.

Parameters:
  • options – Options (non-structured) for complex types, such as ZIP.

  • compression – Desired compression. Can be None or gz, bz2 or xz.

  • **kwargs

    Additional keyword arguments to pass to the function.

Return type:

BytesValue

Returns:

Relative path (from root directory) of the generated file or raw content of the file.

Usage example. Complex case.

from fake import create_inner_txt_file, FAKER

tar_file = FAKER.tar(
    prefix="ttt_archive_",
    options={
        "count": 5,
        "create_inner_file_func": create_inner_txt_file,
        "create_inner_file_args": {
            "prefix": "ttt_file_",
        },
        "directory": "ttt",
    },
)
tar_file(metadata: Optional[MetaData] = None, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, options: Optional[Dict[str, Any]] = None, compression: Optional[Literal['gz', 'bz2', 'xz']] = None, **kwargs) StringValue[source]

Create a TAR archive file.

text(nb_chars: int = 200, suffix: str = '.', allow_overflow: bool = False) str[source]

Generate a text.

text_pdf(nb_pages: int = 1, generator: ~typing.Type[~fake.TextPdfGenerator] = <class 'fake.TextPdfGenerator'>, metadata: ~typing.Optional[~fake.MetaData] = None, **kwargs) bytes[source]

Create a PDF document of a given size.

text_pdf_file(nb_pages: int = 1, generator: ~typing.Type[~fake.TextPdfGenerator] = <class 'fake.TextPdfGenerator'>, metadata: ~typing.Optional[~fake.MetaData] = None, storage: ~typing.Optional[~fake.BaseStorage] = None, basename: ~typing.Optional[str] = None, prefix: ~typing.Optional[str] = None, **kwargs) StringValue[source]

Create a text PDF file.

texts(nb: int = 3) List[str][source]

Generate a list of texts.

tif(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255)) bytes[source]

Create a TIF image of a specified size and colour.

Parameters:
  • size – Tuple of width and height of the image in pixels.

  • color – Colour of the image in RGB format (tuple of three integers).

Returns:

Byte content of the TIF image.

Return type:

bytes

tif_file(size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, extension: Optional[str] = None) StringValue[source]

Create a TIF image file of a specified size and colour.

time(fmt: str = '%H:%M:%S') str[source]

Generate a random time string formatted according to fmt.

Parameters:

fmt – The format to use.

Returns:

A random time string formatted according to fmt.

Return type:

str

tld(tlds: Optional[Tuple[str, ...]] = None) str[source]

Generate a random TLD.

txt_file(nb_chars: Optional[int] = 200, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, text: Optional[str] = None) StringValue[source]

Create a text document file.

url(protocols: Optional[Tuple[str, ...]] = None, tlds: Optional[Tuple[str, ...]] = None, suffixes: Optional[Tuple[str, ...]] = None) str[source]

Generate a random URL.

username() str[source]

Generate a username.

usernames(nb: int = 5) List[str][source]

Generate a list of usernames.

uuid() UUID[source]

Generate a UUID.

uuids(nb: int = 5) List[UUID][source]

Generate a list of UUIDs.

wav(frequency: int = 440, duration: int = 1, volume: Union[float, int] = 0.5, sample_rate: int = 44100) bytes[source]

Create a WAV audio.

Parameters:
  • frequency – The frequency of the tone in Hz.

  • duration – Duration of the tone in seconds.

  • volume – Volume of the tone, scale between 0.0 and 1.0.

  • sample_rate – Sampling rate in Hz.

Returns:

Byte content of the WAV audio.

Return type:

bytes

wav_file(frequency: int = 440, duration: int = 1, volume: Union[float, int] = 0.5, sample_rate: int = 44100, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None) StringValue[source]

Create a WAV audio file.

word() str[source]

Generate a word.

words(nb: int = 5) List[str][source]

Generate a list of words.

year(start_year: int = 1900, end_year: int = 2100) int[source]

Generate a random year between start_year and end_year (inclusive).

Parameters:
  • start_year – The lower bound for the random year.

  • end_year – The upper bound for the random year.

Returns:

A random year as an integer.

Return type:

int

zip(options: Optional[Dict[str, Any]] = None, **kwargs)[source]

Create a ZIP archive file as bytes.

Usage example. A complex case.

from fake import create_inner_txt_file, FAKER

zip_file = FAKER.zip(
    options={
        "count": 5,
        "create_inner_file_func": create_inner_txt_file,
        "create_inner_file_args": {
            "prefix": "zzz_file_",
        },
        "directory": "zzz",
    },
)
zip_file(metadata: Optional[MetaData] = None, storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, options: Optional[Dict[str, Any]] = None, **kwargs) StringValue[source]

Create a ZIP archive file.

Usage example. A simple case.

from fake import FAKER

zip_archive = FAKER.zip()

Usage example. A complex case.

from fake import create_inner_txt_file, FAKER

zip_file = FAKER.zip(
    prefix="zzz_archive_",
    options={
        "count": 5,
        "create_inner_file_func": create_inner_txt_file,
        "create_inner_file_args": {
            "prefix": "zzz_file_",
        },
        "directory": "zzz",
    },
)
class fake.FileRegistry[source]

Bases: object

Stores list StringValue instances.

from fake import FAKER, FILE_REGISTRY

txt_file_1 = FAKER.txt_file()
txt_file_2 = FAKER.txt_file()
...
txt_file_n = FAKER.txt_file()

# The FileRegistry._registry would then contain this:
{
    txt_file_1,
    txt_file_2,
    ...,
    txt_file_n,
}

# Clean up created files as follows:
FILE_REGISTRY.clean_up()
add(string_value: StringValue) None[source]
clean_up() None[source]
remove(string_value: Union[StringValue, str]) bool[source]
search(value: str) Optional[StringValue][source]
class fake.FileSystemStorage(root_path: Optional[Union[str, Path]] = '/tmp', rel_path: Optional[str] = 'tmp', *args, **kwargs)[source]

Bases: BaseStorage

File storage class using pathlib for path handling.

Usage example:

from fake import FAKER, FileSystemStorage

storage = FileSystemStorage()
docx_file = storage.generate_filename(prefix="zzz_", extension="docx")
storage.write_bytes(docx_file, FAKER.docx())

Initialization with params:

from fake import FAKER, FileSystemStorage

storage = FileSystemStorage()
docx_file = FAKER.docx_file(storage=storage)
abspath(filename: str) str[source]

Return absolute path.

exists(filename: str) bool[source]

Check if file exists.

generate_filename(extension: str, prefix: Optional[str] = None, basename: Optional[str] = None) str[source]

Generate filename.

relpath(filename: str) str[source]

Return relative path.

Delete the file.

write_bytes(filename: str, data: bytes) int[source]

Write bytes.

write_text(filename: str, data: str, encoding: Optional[str] = None) int[source]

Write text.

class fake.GraphicPdfGenerator(faker: Faker)[source]

Bases: object

Graphic PDF generatr.

Usage example:

from pathlib import Path
from fake import FAKER, GraphicPdfGenerator

Path("/tmp/graphic_example.pdf").write_bytes(
    FAKER.pdf(nb_pages=100, generator=GraphicPdfGenerator)
)
create(nb_pages: int = 1, image_size: Tuple[int, int] = (100, 100), image_color: Tuple[int, int, int] = (255, 0, 0), **kwargs) bytes[source]
image_color: Tuple[int, int, int]
image_size: Tuple[int, int]
nb_pages: int
class fake.LazyAttribute(func)[source]

Bases: object

class fake.LazyFunction(func)[source]

Bases: object

class fake.LazyStringTemplate(template: str, wrap_chars_after: Optional[int] = None, faker: Optional[Faker] = None)[source]

Bases: StringTemplateMixin

LazyStringTemplate.

Usage example:

from fake import FAKER, LazyStringTemplate

template = '''
    {date(start_date='-7d')},
    Dear {name},
    {sentence(nb_words=25)}
    Best regards,
    {name}
'''
string_template = LazyStringTemplate(template)
print(string_template.render())

Integration with providers:

from fake import FAKER, LazyStringTemplate

template = '''
    {date(start_date='-7d')},
    Dear {name},
    {sentence(nb_words=25)}
    Best regards,
    {name}
'''
string_template = LazyStringTemplate(template)

FAKER.docx_file(texts=[str(string_template)])
FAKER.eml_file(content=str(string_template))
FAKER.txt_file(text=str(string_template))
FAKER.text_pdf_file(texts=[str(string_template) for _ in range(10)])
class fake.MetaData[source]

Bases: object

add_content(content: Union[str, List[str]]) None[source]
content: Optional[str]
class fake.ModelFactory(**kwargs)[source]

Bases: object

ModelFactory.

class Meta[source]

Bases: object

get_or_create = ('id',)
classmethod create(**kwargs)[source]
classmethod create_batch(count, **kwargs)[source]
classmethod save(instance)[source]

Save the instance.

class fake.OdtGenerator(faker: Faker)[source]

Bases: object

OdtGenerator - generates an ODT file with text.

Usage example:

from pathlib import Path
from fake import FAKER

Path("/tmp/example.odt").write_bytes(
    OdtGenerator(FAKER).create(nb_pages=100)
)
create(nb_pages: Optional[int] = None, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None) bytes[source]
class fake.PostSave(func, *args, **kwargs)[source]

Bases: object

execute(instance)[source]
class fake.PreInit(func, *args, **kwargs)[source]

Bases: object

execute(data: Dict[str, Any]) None[source]
class fake.PreSave(func, *args, **kwargs)[source]

Bases: object

execute(instance)[source]
class fake.PydanticModelFactory(**kwargs)[source]

Bases: ModelFactory

Pydantic ModelFactory.

class fake.SQLAlchemyModelFactory(**kwargs)[source]

Bases: ModelFactory

SQLAlchemy ModelFactory.

classmethod create(**kwargs)[source]
classmethod save(instance)[source]

Save the instance.

class fake.StringTemplate(template: str, wrap_chars_after: Optional[int] = None, faker: Optional[Faker] = None)[source]

Bases: str, StringTemplateMixin

LazyStringTemplate.

Usage example:

from fake import FAKER, StringTemplate

template = '''
    {date(start_date='-7d')},
    Dear {name},
    {sentence(nb_words=25)}
    Best regards,
    {name}
'''
string_template = StringTemplate(template)
print(string_template)

Integration with providers:

from fake import FAKER, StringTemplate

template = '''
    {date(start_date='-7d')},
    Dear {name},
    {sentence(nb_words=25)}
    Best regards,
    {name}
'''
string_template = StringTemplate(template)

FAKER.docx_file(
    texts=[StringTemplate(template) for _ in range(10)]
)
FAKER.eml_file(content=string_template)
FAKER.txt_file(text=string_template)
FAKER.text_pdf_file(
    texts=[StringTemplate(template) for _ in range(10)]
)
class fake.StringValue(value: str, *args, **kwargs)[source]

Bases: str

data: Dict[str, Any]
class fake.SubFactory(factory_class, **kwargs)[source]

Bases: object

class fake.TextPdfGenerator(faker: Faker)[source]

Bases: object

Text PDF generatr.

Usage example:

from pathlib import Path
from fake import FAKER, TextPdfGenerator

Path("/tmp/text_example.pdf").write_bytes(
    FAKER.pdf(nb_pages=100, generator=TextPdfGenerator)
)
create(nb_pages: Optional[int] = None, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None, **kwargs) bytes[source]
nb_pages: int
texts: List[str]
class fake.TortoiseModelFactory(**kwargs)[source]

Bases: ModelFactory

Tortoise ModelFactory.

classmethod create(**kwargs)[source]
classmethod save(instance)[source]

Save the instance.

fake.create_inner_bmp_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), **kwargs) StringValue[source]

Create inner BMP file.

fake.create_inner_docx_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, nb_pages: Optional[int] = 1, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None, **kwargs) StringValue[source]

Create inner DOCX file.

fake.create_inner_eml_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, options: Optional[Dict[str, Any]] = None, content: Optional[str] = None, subject: Optional[str] = None, metadata: Optional[MetaData] = None, **kwargs) StringValue[source]

Create inner EML file.

fake.create_inner_gif_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), **kwargs) StringValue[source]

Create inner GIF file.

fake.create_inner_jpg_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (128, 128, 128), **kwargs) StringValue[source]

Create inner JPG file.

fake.create_inner_odt_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, nb_pages: Optional[int] = 1, texts: Optional[List[str]] = None, metadata: Optional[MetaData] = None, **kwargs) StringValue[source]

Create inner ODT file.

fake.create_inner_pdf_file(storage: ~typing.Optional[~fake.BaseStorage] = None, basename: ~typing.Optional[str] = None, prefix: ~typing.Optional[str] = None, nb_pages: ~typing.Optional[int] = 1, generator: ~typing.Union[~typing.Type[~fake.TextPdfGenerator], ~typing.Type[~fake.GraphicPdfGenerator]] = <class 'fake.GraphicPdfGenerator'>, metadata: ~typing.Optional[~fake.MetaData] = None, **kwargs) StringValue[source]

Create inner PDF file.

fake.create_inner_png_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), **kwargs) StringValue[source]

Create inner PNG file.

fake.create_inner_ppm_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), **kwargs) StringValue[source]

Create inner PPM file.

fake.create_inner_svg_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), **kwargs) StringValue[source]

Create inner SVG file.

fake.create_inner_tar_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, options: Optional[Dict[str, Any]] = None, compression: Optional[Literal['gz', 'bz2', 'xz']] = None, metadata: Optional[MetaData] = None, **kwargs) StringValue[source]

Create inner TAR file.

fake.create_inner_text_pdf_file(storage: ~typing.Optional[~fake.BaseStorage] = None, basename: ~typing.Optional[str] = None, prefix: ~typing.Optional[str] = None, nb_pages: ~typing.Optional[int] = 1, generator: ~typing.Type[~fake.TextPdfGenerator] = <class 'fake.TextPdfGenerator'>, metadata: ~typing.Optional[~fake.MetaData] = None, **kwargs) StringValue[source]

Create inner text PDF file.

fake.create_inner_tif_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), **kwargs) StringValue[source]

Create inner TIF file.

fake.create_inner_txt_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, text: Optional[str] = None, **kwargs) StringValue[source]

Create inner TXT file.

fake.create_inner_wav_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, frequency: int = 440, duration: int = 1, volume: Union[float, int] = 0.5, sample_rate: int = 44100, **kwargs) StringValue[source]

Create inner WAV file.

fake.create_inner_zip_file(storage: Optional[BaseStorage] = None, basename: Optional[str] = None, prefix: Optional[str] = None, options: Optional[Dict[str, Any]] = None, metadata: Optional[MetaData] = None, **kwargs) StringValue[source]

Create inner ZIP file.

fake.fill_dataclass(dataclass_type: Type) Any

Fill dataclass with data.

fake.fill_pydantic_model(object_type: Type) Any
fake.format_type_hint(type_hint) str[source]

Format the type hint for display.

fake.fuzzy_choice_create_inner_file(func_choices: List[Tuple[Callable[[...], StringValue], Dict[str, Any]]], **kwargs) StringValue[source]

Create inner file from given list of function choices.

Parameters:
  • func_choices – List of functions to choose from.

  • **kwargs

    Additional keyword arguments to pass to the function.

Return type:

StringValue

Returns:

StringValue instance.

Usage example:

from fake import (
    FAKER,
    FileSystemStorage,
    create_inner_docx_file,
    create_inner_png_file,
    create_inner_txt_file,
    fuzzy_choice_create_inner_file,
)

STORAGE = FileSystemStorage()

kwargs = {"storage": STORAGE}
file = fuzzy_choice_create_inner_file(
    [
        (create_inner_docx_file, kwargs),
        (create_inner_png_file, kwargs),
        (create_inner_txt_file, kwargs),
    ]
)

You could use it in archives to make a variety of different file types within the archive.

from fake import (
    FAKER,
    FileSystemStorage,
    create_inner_docx_file,
    create_inner_png_file,
    create_inner_txt_file,
    fuzzy_choice_create_inner_file,
)

STORAGE = FileSystemStorage()

kwargs = {"storage": STORAGE}
file = FAKER.zip_file(
    prefix="zzz_archive_",
    options={
        "count": 50,
        "create_inner_file_func": fuzzy_choice_create_inner_file,
        "create_inner_file_args": {
            "func_choices": [
                (create_inner_docx_file, kwargs),
                (create_inner_png_file, kwargs),
                (create_inner_txt_file, kwargs),
            ],
        },
        "directory": "zzz",
    }
)
fake.get_argparse_type(param_type) Any[source]

Get the corresponding argparse type for a given parameter type.

fake.get_provider_args(func: Callable) Dict[str, Any][source]

Retrieve the argument list and types for a provider function by inspecting its signature.

fake.get_provider_defaults(func: Callable) Dict[str, Any][source]

Retrieve the argument list and defaults for a provider function by inspecting its signature.

fake.is_optional_type(type_hint) bool[source]

Check if the type hint is an Optional.

fake.list_create_inner_file(func_list: List[Tuple[Callable[[...], StringValue], Dict[str, Any]]], **kwargs) List[StringValue][source]

Generates multiple files based on the provided list of functions and arguments.

Parameters:
  • func_list – List of tuples, each containing a function to generate a file and its arguments.

  • **kwargs

    Additional keyword arguments to pass to the functions.

Return type:

List[StringValue]

Returns:

List of generated file names.

Usage example:

from fake import (
    FAKER,
    FileSystemStorage,
    create_inner_docx_file,
    create_inner_txt_file,
    list_create_inner_file,
)

file = FAKER.zip_file(
    basename="alice-looking-through-the-glass",
    options={
        "create_inner_file_func": list_create_inner_file,
        "create_inner_file_args": {
            "func_list": [
                (create_inner_docx_file, {"basename": "doc"}),
                (create_inner_txt_file, {"basename": "doc_metadata"}),
                (create_inner_txt_file, {"basename": "doc_isbn"}),
            ],
        },
    }
)

Note, that while all other inner functions return back StringValue value, list_create_inner_file returns back a List[StringValue] value.

Notably, all inner functions were designed to support archives (such as ZIP, TAR and EML, but the list may grow in the future). If the inner function passed in the create_inner_file_func argument returns a List of StringValue values, the option argument is being ignored and generated files are simply limited to what has been passed in the func_list list of tuples.

fake.main() None[source]
fake.organize_providers(provider_tags) Dict[str, Any][source]

Organize providers by category for easier navigation.

fake.post_save(func)[source]
fake.pre_init(func)[source]
fake.pre_save(func)[source]
fake.provider(*args: Any, tags: Optional[Tuple[str, ...]] = None) Callable[source]
fake.run_async_in_thread(coroutine: Coroutine) Awaitable[source]

Run an asynchronous coroutine in a separate thread.

Parameters:

coroutine – An asyncio coroutine to be run.

Returns:

The result of the coroutine.

Return type:

Awaitable

fake.slugify(value: str, separator: str = '') str[source]

Slugify.

fake.trait(func)[source]
fake.wrap_text(text: str, wrap_chars_after: int) str[source]
fake.xor_transform(val: str, key: int = 10) str[source]

Simple, deterministic string encoder/decoder.

Usage example:

val = "abcd"
encoded_val = xor_transform(val)
decoded_val = xor_transform(encoded_val)