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.

abstractmethod abspath(filename: Any) str[source]

Return absolute path.

abstractmethod exists(filename: Any) bool[source]

Check if file exists.

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

Generate a random alphanumeric sequence.

abstractmethod generate_filename(extension: str, prefix: str | None = None, basename: str | None = None) Any[source]

Generate filename.

abstractmethod relpath(filename: Any) str[source]

Return relative path.

Delete the file.

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

Write bytes.

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

Write text.

class fake.CLI(faker: Faker | None = 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: int | None = None, texts: List[str] | None = None, metadata: MetaData | None = None) bytes[source]
class fake.EpubGenerator(faker: Faker)[source]

Bases: object

EpubGenerator - generates a minimal EPUB file with text pages.

create(nb_pages: int | None = None, texts: List[str] | None = None, metadata: MetaData | None = None) bytes[source]
class fake.Factory(faker: Faker | None = None)[source]

Bases: object

Factory.

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

Bases: object

class fake.Faker(alias: str | None = None, seed: int | None = 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.

Parameters:

length – Length of the bytes to generate. Defaults to 16.

Returns:

Byte content of the random bytes.

Return type:

bytes

bin_file(length: int = 16, storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = 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. Defaults to (100, 100).

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

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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, extension: str | None = None) StringValue[source]

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

Parameters:
  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • extension – File extension. Defaults to None, in which case the image_format value is used.

Returns:

StringValue containing the relative path of the generated BMP file.

Return type:

StringValue

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

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

Usage example:

from fake import FAKER
FAKER.randomise_string(value="10.####/####-####")
# '10.4613/4636-8596'
FAKER.randomise_string(value="???? ##")
# '1234 AB'
Parameters:
  • value – Input string containing ? and # placeholders.

  • letters – String of characters to use for ? replacement. Defaults to uppercase ASCII letters.

  • digits – String of characters to use for # replacement. Defaults to digits 0-9.

Returns:

String with ? replaced by random letters and # by random digits.

Return type:

str

city() str[source]

Get a random city.

Returns:

A random city name.

Return type:

str

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

Generate a random company email.

Parameters:

domain_names – List of domains to randomly choose from. If not given or None, random words are used.

Returns:

Company email.

Return type:

str

company_emails(nb: int = 5, domain_names: Tuple[str, ...] | None = None) List[str][source]

Generate a list of random company emails.

Parameters:
  • nb – Number of emails to generate.

  • domain_names – List of domains to randomly choose from. If not given or None, random words are used.

Returns:

List of emails.

Return type:

List[str]

country() str[source]

Get a random country.

Returns:

A random country name.

Return type:

str

country_code() str[source]

Get a random country code.

Returns:

A random country code.

Return type:

str

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.

Both start_date and end_date support:

  1. ISO format dates: - ‘YYYY-MM-DD’ (e.g., ‘2000-01-01’) - ‘YYYY-MM-DD HH:MM:SS’ (e.g., ‘2000-01-01 12:00:00’)

  2. Relative shorthand notation: [+/-][number][unit]

    Units: - d days - h hours - m minutes - w weeks - mo months - y years

    Deprecated (still work, emit warnings): H -> h, M -> m

    Sign: ‘+’ for future, ‘-’ for past, or omit ‘+’ for future

    Special: ‘now’, ‘today’ for current datetime

Shorthand notation examples:

  • ‘-7d’: 7 days ago

  • ‘+3d’ or ‘3d’: 3 days from now

  • ‘-2w’: 2 weeks ago

  • ‘+1mo’: 1 month from now

  • ‘-1y’: 1 year ago

  • ‘-24h’: 24 hours ago

  • ‘+2h’: 2 hours from now

  • ‘-30m’: 30 minutes ago

  • ‘today’ or ‘now’: current datetime

ISO format examples:

  • ‘2000-01-01’: January 1, 2000

  • ‘2025-12-31’: December 31, 2025

  • ‘2000-01-01 00:00:00’: with time component

Usage example:

FAKER.date()  # random date between 7 days ago and today
FAKER.date('-7d', '+0d')  # same as above (explicit)
FAKER.date('-30d', '-1d')  # between 30 days ago and yesterday
FAKER.date('+1d', '+7d')  # between tomorrow and next week
FAKER.date('today', '+3d')  # between today and 3 days from now
FAKER.date('-2w', '+1w')  # within 3-week window around now
FAKER.date(
    '-3mo', '+6mo'
)  # between 3 months ago and 6 months from now
FAKER.date('-1y', '+1y')  # within 1 year window around now
FAKER.date('2000-01-01', '2025-12-31')  # ISO date range
FAKER.date('-1d', '-1d')  # yesterday only
FAKER.date('-365d', 'today')  # in the past year
FAKER.date('+1d', '+30d')  # in the next month
Parameters:
  • start_date – The start date (ISO format or shorthand notation).

  • end_date – The end date (ISO format or 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.

Both start_date and end_date support:

  1. ISO format dates: - ‘YYYY-MM-DD’ (e.g., ‘2000-01-01’) - ‘YYYY-MM-DD HH:MM:SS’ (e.g., ‘2000-01-01 12:00:00’)

  2. Relative shorthand notation: [+/-][number][unit]

    Units: - d days - h hours - m minutes - w weeks - mo months - y years

    Deprecated (still work, emit warnings): H -> h, M -> m

    Sign: ‘+’ for future, ‘-’ for past, or omit ‘+’ for future

    Special: ‘now’, ‘today’ for current datetime

Shorthand notation examples:

  • ‘-7d’: 7 days ago

  • ‘+3d’ or ‘3d’: 3 days from now

  • ‘-2w’: 2 weeks ago

  • ‘+1mo’: 1 month from now

  • ‘-1y’: 1 year ago

  • ‘-24h’: 24 hours ago

  • ‘+2h’: 2 hours from now

  • ‘-30m’: 30 minutes ago

  • ‘today’ or ‘now’: current datetime

ISO format examples:

  • ‘2000-01-01’: January 1, 2000

  • ‘2025-12-31 23:59:59’: with time component

Usage example:

FAKER.date_time()  # random datetime between 7 days ago and now
FAKER.date_time('-7d', '+0d')  # same as above (explicit)
FAKER.date_time('-24h', '+0h')  # in the past 24 hours
FAKER.date_time('-30m', '+30m')  # within 1-hour window around now
FAKER.date_time('-2w', '+1w')  # within 3-week window
FAKER.date_time('-3mo', '+6mo')  # within 9-month window
FAKER.date_time('-1y', '+1y')  # within 1 year window
FAKER.date_time('today', '+1d')  # between now and tomorrow
FAKER.date_time('+1h', '+4h')  # between 1-4 hours from now
FAKER.date_time('-1d', 'now')  # since yesterday
FAKER.date_time('-2h', '-1h')  # between 2-1 hours ago
FAKER.date_time('+15m', '+45m')  # in 15-45 minutes
FAKER.date_time('-365d', 'today')  # in the past year
FAKER.date_time(
    '2000-01-01', '2025-12-31'
)  # ISO date range
Parameters:
  • start_date – The start datetime (ISO format or shorthand notation). Defaults to -7d.

  • end_date – The end datetime (ISO format or shorthand notation). Defaults to +0d.

  • tzinfo – The timezone. Defaults to timezone.utc.

Returns:

A string representing the formatted datetime.

Return type:

datetime

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

Generate a random dir path.

Parameters:

depth – Depth to add to dir path. Defaults to 1.

Returns:

Dir path.

Return type:

str

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

Create a DOCX document.

Usage example without params:

FAKER.docx()

Usage example with params:

FAKER.docx(texts=("Page 1", "Page 2", "Page 3"))
FAKER.docx(nb_pages=5)
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

Returns:

Byte content of the DOCX document.

Return type:

bytes

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

Create a DOCX document file.

Usage example without params:

FAKER.docx_file()

Usage example with params:

FAKER.docx_file(nb_pages=5, prefix="custom_docx_")
FAKER.docx_file(texts=["First page", "Second page", "Third page"])
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

Returns:

StringValue containing the relative path of the generated DOCX file.

Return type:

StringValue

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

Generate a random domain name.

Parameters:

tlds – List of TLDs to use. If not given or None, a default list of TLDs is used.

Returns:

Domain name.

Return type:

str

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

Generate a random email.

Parameters:

domain_names – List of domains to randomly choose from. If not given or None, random words are used.

Returns:

Email.

Return type:

str

emails(nb: int = 5, domain_names: Tuple[str, ...] | None = None) List[str][source]

Generate a list of random emails.

Parameters:
  • nb – Number of emails to generate.

  • domain_names – List of domains to randomly choose from. If not given or None, random words are used.

Returns:

List of emails.

Return type:

List[str]

eml(options: Dict[str, Any] | None = None, content: str | None = None, subject: str | None = None, cte_type: str | None = None, policy: Policy | None = 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.

  • cte_type – Content-Transfer-Encoding (CTE) type.

  • policy – Email message policy.

  • **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: MetaData | None = None, storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, options: Dict[str, Any] | None = None, content: str | None = None, subject: str | None = None, cte_type: str | None = None, policy: Policy | None = None, **kwargs) StringValue[source]

Create an EML file.

Parameters:
  • metadata – Metadata for the EML file. Defaults to None.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • options – Additional options for EML generation. Defaults to None.

  • content – Content of the email. Defaults to None.

  • subject – Subject of the email. Defaults to None.

  • cte_type – Content-Transfer-Encoding type. Defaults to None.

  • policy – Email policy to use. Defaults to None.

  • **kwargs

    Additional keyword arguments.

Returns:

StringValue containing the relative path of the generated EML file.

Return type:

StringValue

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

Create a minimal EPUB document.

Usage example without params:

FAKER.epub()

Usage example with params:

FAKER.epub(texts=("Page 1", "Page 2", "Page 3"))
FAKER.epub(nb_pages=5)
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

Returns:

Byte content of the minimal EPUB document.

Return type:

bytes

epub_file(nb_pages: int = 1, texts: List[str] | None = None, metadata: MetaData | None = None, storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None) StringValue[source]

Create a EPUB document file.

Usage example without params:

FAKER.epub_file()

Usage example with params:

FAKER.epub_file(nb_pages=5, prefix="custom_epub_")
FAKER.epub_file(texts=["First page", "Second page", "Third page"])
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

Returns:

StringValue containing the relative path of the generated EPUB file.

Return type:

StringValue

file_extension() str[source]

Generate a random extension.

Returns:

File extension.

Return type:

str

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

Generate a random filename.

Parameters:
  • prefix – Prefix to add to filename. Defaults to empty string.

  • extension – Extension to add to filename. Defaults to ‘.txt’.

Returns:

Filename.

Return type:

str

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

Generate a random file path.

Parameters:
  • prefix – Prefix to add to file path. Defaults to empty string.

  • extension – Extension to add to file path. Defaults to ‘.txt’.

Returns:

File path.

Return type:

str

first_name() str[source]

Generate a first name.

Returns:

First name.

Return type:

str

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

Generate a list of first names.

Parameters:

nb – Number of first names to generate.

Returns:

List of first names.

Return type:

List[str]

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

Generate a random free email.

Parameters:

domain_names – List of domains to randomly choose from. If not given or None, random words are used.

Returns:

Free email.

Return type:

str

free_email_domain() str[source]

Generate a random free email domain.

Returns:

Free email domain.

Return type:

str

free_emails(nb: int = 5, domain_names: Tuple[str, ...] | None = None) List[str][source]

Generate a list of random free emails.

Parameters:
  • nb – Number of emails to generate.

  • domain_names – List of domains to randomly choose from. If not given or None, random words are used.

Returns:

List of emails.

Return type:

List[str]

generic_file(content: bytes | str | StringTemplate | LazyStringTemplate, extension: str, storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None) StringValue[source]

Create a generic file.

Parameters:
  • content – Content to write to the file. Can be bytes, string, StringTemplate, or LazyStringTemplate. Templates are rendered fresh on each call before writing.

  • extension – File extension.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

Returns:

StringValue containing the relative path of the generated file.

Return type:

StringValue

geo_location() str[source]

Get a random geo-location.

Returns:

A random geo-location name.

Return type:

str

static get_by_alias(alias: str) Faker | None[source]
static get_by_uid(uid: str) Faker | None[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. Defaults to (100, 100).

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

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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, extension: str | None = None) StringValue[source]

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

Parameters:
  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • extension – File extension. Defaults to None, in which case the image_format value is used.

Returns:

StringValue containing the relative path of the generated GIF file.

Return type:

StringValue

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

Generate a random valid IBAN number.

Usage example without params:

from fake import FAKER
FAKER.iban()
# 'BA36243707341183493142'

Usage example with params:

from fake import FAKER
FAKER.iban(country_code="DE", bank_length=8, account_length=10)
# 'DE45984597116997556579'
Parameters:
  • country_code – Optional country code. If None, a random country code is selected. Defaults to None.

  • bank_length – Length of the bank identifier part. Defaults to 8.

  • account_length – Length of the account number part. Defaults to 10.

Returns:

A random valid IBAN number.

Return type:

str

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.

Parameters:
  • image_format – Format of the image. Defaults to “png”.

  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

Returns:

Byte content of the image.

Return type:

bytes

Raises:

ValueError – If the image format is not supported.

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

Generate a random image URL.

Parameters:
  • width – Width of the image. Defaults to 800.

  • height – Height of the image. Defaults to 600.

  • service_url – Service URL. If not given or None, randomly picked service URL is used.

Returns:

Image URL.

Return type:

str

ipv4() str[source]

Generate a random IP v4.

Returns:

Random IP v4.

Return type:

str

isbn10() str[source]

Generate a random valid ISBN-10.

Returns:

A random valid ISBN-10 number in the format ‘XXX-XXX-XXX-X’.

Return type:

str

isbn13() str[source]

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

Returns:

A random valid ISBN-13 number in the format ‘XXX-X-XXX-XXXXX-X’.

Return type:

str

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. Defaults to (100, 100).

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

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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, extension: str | None = None) StringValue[source]

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

Parameters:
  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • extension – File extension. Defaults to None, in which case the image_format value is used.

Returns:

StringValue containing the relative path of the generated JPG file.

Return type:

StringValue

last_name() str[source]

Generate a last name.

Returns:

Last name.

Return type:

str

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

Generate a list of last names.

Parameters:

nb – Number of last names to generate.

Returns:

List of last names.

Return type:

List[str]

lat() float

Generate a random latitude.

Returns:

A random latitude.

Return type:

float

latitude() float[source]

Generate a random latitude.

Returns:

A random latitude.

Return type:

float

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

Generate a random (latitude, longitude) pair.

Returns:

A tuple containing a random latitude and longitude.

Return type:

Tuple[float, float]

latlng() Tuple[float, float]

Generate a random (latitude, longitude) pair.

Returns:

A tuple containing a random latitude and longitude.

Return type:

Tuple[float, float]

latlon() Tuple[float, float]

Generate a random (latitude, longitude) pair.

Returns:

A tuple containing a random latitude and longitude.

Return type:

Tuple[float, float]

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

Lazy string template.

Generate a string by substituting placeholders in a template with fake data or provided values.

Usage example:

from fake import FAKER
tpl = FAKER.lazy_string_template(
    "Hello {first_name}! I have two words for you: {words(nb=2)}"
)
print(tpl)
# "Hello Mike! I have two words for you: ['idea', 'first']"
print(tpl)
# Hello Lars! I have two words for you: ['be', 'if']
Parameters:
  • template – Template string containing placeholders in curly braces (e.g., ‘{name}’, ‘{words(nb=2)}’). Placeholders should match Faker method names or be overridden by kwargs.

  • wrap_chars_after – Number of characters to wrap around.

  • faker – Faker instance to use.

Return type:

LazyStringTemplate

Returns:

String with placeholders replaced with correspondent fake values.

lng() float

Generate a random longitude.

Returns:

A random longitude.

Return type:

float

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.

Returns:

A random locale.

Return type:

str

lon() float

Generate a random longitude.

Returns:

A random longitude.

Return type:

float

longitude() float[source]

Generate a random longitude.

Returns:

A random longitude.

Return type:

float

mime_type() str[source]

Generate a random mime type.

Returns:

Mime type.

Return type:

str

name() str[source]

Generate a name.

Returns:

Name.

Return type:

str

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

Generate a list of names.

Parameters:

nb – Number of names to generate.

Returns:

List of names.

Return type:

List[str]

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

Create a ODT document.

Usage example without params:

FAKER.odt()

Usage example with params:

FAKER.odt(texts=("Page 1", "Page 2", "Page 3"))
FAKER.odt(nb_pages=5)
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

Returns:

Byte content of the ODT document.

Return type:

bytes

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

Create a ODT document file.

Usage example without params:

FAKER.odt_file()

Usage example with params:

FAKER.odt_file(nb_pages=5, prefix="custom_odt_")
FAKER.odt_file(texts=["First page", "Second page", "Third page"])
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

Returns:

StringValue containing the relative path of the generated ODT file.

Return type:

StringValue

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

Generate a paragraph.

Parameters:

nb_sentences – Number of sentences to generate.

Returns:

Paragraph.

Return type:

str

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

Generate a list of paragraphs.

Parameters:

nb – Number of paragraphs to generate.

Returns:

List of paragraphs.

Return type:

List[str]

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. Defaults to 1.

  • min_upper – Minimum number of uppercase letters. Defaults to 1.

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

  • min_special – Minimum number of special characters. Defaults to 0.

Returns:

Random password string.

Return type:

str

Raises:

ValueError – if the total length is less than the sum of all minimum character constraints.

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

Create a PDF document of a given size.

Parameters:
  • nb_pages – The number of pages to generate. Defaults to 1.

  • generator – The PDF generator to use. Defaults to GraphicPdfGenerator.

  • metadata – The metadata to use. Defaults to None.

  • **kwargs

    Additional arguments to pass to generator.

Returns:

A bytes object representing the PDF document.

Return type:

bytes

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

Create a PDF file.

Usage example without params:

FAKER.pdf_file()

Usage example with params:

FAKER.pdf_file(nb_pages=5, prefix="custom_pdf_")
Parameters:
  • nb_pages – Number of pages in the PDF. Defaults to 1.

  • generator – PDF generator class to use. Defaults to GraphicPdfGenerator.

  • metadata – Metadata for the PDF. Defaults to None.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Can also be a StringTemplate or LazyStringTemplate. Defaults to None.

  • prefix – Prefix for the file name. Can also be a StringTemplate or LazyStringTemplate. Defaults to None.

  • **kwargs

    Additional keyword arguments to pass to the PDF generator.

Returns:

StringValue containing the relative path of the generated PDF file.

Return type:

StringValue

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. Defaults to (100, 100).

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

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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, extension: str | None = None) StringValue[source]

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

Parameters:
  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • extension – File extension. Defaults to None, in which case the image_format value is used.

Returns:

StringValue containing the relative path of the generated PNG file.

Return type:

StringValue

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. Defaults to (100, 100).

  • color – Colour of the image in RGB format, tuple of three integers: (0-255, 0-255, 0-255). Defaults to (0, 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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, extension: str | None = None) StringValue[source]

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

Parameters:
  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • extension – File extension. Defaults to None, in which case the image_format value is used.

Returns:

StringValue containing the relative path of the generated PPM file.

Return type:

StringValue

pybool() bool[source]

Generate a random boolean.

Returns:

Random boolean.

Return type:

bool

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 – if left_digits or right_digits is less than 0.

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

Generate a random float number.

Parameters:
  • min_value – Min value of the generated number. Defaults to 0.

  • max_value – Max value of the generated number. Defaults to 10.

Returns:

Random float number.

Return type:

float

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

Generate a random integer.

Parameters:
  • min_value – Min value of the generated integer. Defaults to 0.

  • max_value – Max value of the generated integer. Defaults to 9999.

Returns:

Random integer within the range [min_value, max_value].

Return type:

int

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

Generate a random string.

Parameters:

nb_chars – Number of characters to generate.

Returns:

Random string.

Return type:

str

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

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

Example usage:

from fake import FAKER
FAKER.random_choice(("Art", "Photography", "Generative AI"))
# 'Photography'
Parameters:

elements – A list or tuple of elements to choose from.

Returns:

A randomly selected element from the input list.

Return type:

T

random_element(elements: Sequence[T]) T

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

Example usage:

from fake import FAKER
FAKER.random_choice(("Art", "Photography", "Generative AI"))
# 'Photography'
Parameters:

elements – A list or tuple of elements to choose from.

Returns:

A randomly selected element from the input list.

Return type:

T

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

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

Example usage:

from fake import FAKER
FAKER.random_sample(("Art", "Photography", "Generative AI"), 2)
# ['Photography', 'Art']
random_sample(elements: Sequence[T], length: int) List[T][source]

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

Example usage:

from fake import FAKER
FAKER.random_sample(("Art", "Photography", "Generative AI"), 2)
# ['Photography', 'Art']
randomise_string(value: str, letters: str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', digits: str = '0123456789') str[source]

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

Usage example:

from fake import FAKER
FAKER.randomise_string(value="10.####/####-####")
# '10.4613/4636-8596'
FAKER.randomise_string(value="???? ##")
# '1234 AB'
Parameters:
  • value – Input string containing ? and # placeholders.

  • letters – String of characters to use for ? replacement. Defaults to uppercase ASCII letters.

  • digits – String of characters to use for # replacement. Defaults to digits 0-9.

Returns:

String with ? replaced by random letters and # by random digits.

Return type:

str

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

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

Usage example:

from fake import FAKER
FAKER.randomise_string(value="10.####/####-####")
# '10.4613/4636-8596'
FAKER.randomise_string(value="???? ##")
# '1234 AB'
Parameters:
  • value – Input string containing ? and # placeholders.

  • letters – String of characters to use for ? replacement. Defaults to uppercase ASCII letters.

  • digits – String of characters to use for # replacement. Defaults to digits 0-9.

Returns:

String with ? replaced by random letters and # by random digits.

Return type:

str

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

Create an RTF document.

Usage example without params:

FAKER.rtf()

Usage example with params:

FAKER.rtf(texts=("Page 1", "Page 2", "Page 3"))
FAKER.rtf(nb_pages=5)
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

Returns:

Byte content of the RTF document.

Return type:

bytes

rtf_file(nb_pages: int = 1, texts: List[str] | None = None, metadata: MetaData | None = None, storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None) StringValue[source]

Create an RTF document file.

Usage example without params:

FAKER.rtf_file()

Usage example with params:

FAKER.rtf_file(nb_pages=5, prefix="custom_rtf_")
FAKER.rtf_file(texts=["First page", "Second page", "Third page"])
Parameters:
  • nb_pages – Number of pages to show. Defaults to 1.

  • texts – List of texts to show. Defaults to None.

  • metadata – Metadata to show. Defaults to None.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

Returns:

StringValue containing the relative path of the generated RTF file.

Return type:

StringValue

seed(seed: int | None) None[source]

Reset the RNG state with a new seed.

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

Generate a sentence.

Parameters:
  • nb_words – Number of words to generate.

  • suffix – Suffix to add to sentence. Defaults to ..

Returns:

Sentence.

Return type:

str

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

Generate a list of sentences.

Parameters:

nb – Number of sentences to generate.

Returns:

List of sentences.

Return type:

List[str]

slug() str[source]

Generate a slug.

Returns:

Slug.

Return type:

str

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

Generate a list of slugs.

Parameters:

nb – Number of slugs to generate.

Returns:

List of slugs.

Return type:

List[str]

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

String template.

Generate a string by substituting placeholders in a template with fake data or provided values.

Usage example:

from fake import FAKER
FAKER.string_template(
    "Hello {first_name}! I have two words for you: {words(nb=2)}"
)
# "Hello Mike! I have two words for you: ['idea', 'first']"
Parameters:
  • template – Template string containing placeholders in curly braces (e.g., ‘{name}’, ‘{words(nb=2)}’). Placeholders should match Faker method names or be overridden by kwargs.

  • wrap_chars_after – Number of characters to wrap around.

  • faker – Faker instance to use.

Return type:

str

Returns:

String with placeholders replaced with correspondent fake values.

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. Defaults to (100, 100).

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

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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, extension: str | None = None) StringValue[source]

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

Parameters:
  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • extension – File extension. Defaults to None, in which case the image_format value is used.

Returns:

StringValue containing the relative path of the generated SVG file.

Return type:

StringValue

tar(options: Dict[str, Any] | None = None, compression: Literal['gz', 'bz2', 'xz'] | None = 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: MetaData | None = None, storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, options: Dict[str, Any] | None = None, compression: Literal['gz', 'bz2', 'xz'] | None = 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.

Parameters:
  • nb_chars – Number of characters to generate.

  • suffix – Suffix to add to text. Defaults to ..

  • allow_overflow – Allow overflow. Defaults to False.

Returns:

Text.

Return type:

str

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

Create a PDF document of a given size.

Parameters:
  • nb_pages – The number of pages to generate. Defaults to 1.

  • generator – The PDF generator to use. Defaults to TextPdfGenerator.

  • metadata – The metadata to use. Defaults to None.

  • **kwargs

    Additional arguments to pass to generator.

Returns:

A bytes object representing the PDF document.

Return type:

bytes

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

Create a text PDF file.

Usage example without params:

FAKER.text_pdf_file()

Usage example with params:

FAKER.text_pdf_file(nb_pages=5, prefix="custom_text_pdf_")
Parameters:
  • nb_pages – Number of pages in the PDF. Defaults to 1.

  • generator – PDF generator class to use. Defaults to TextPdfGenerator.

  • metadata – Metadata for the PDF. Defaults to None.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • **kwargs

    Additional keyword arguments to pass to the PDF generator.

Returns:

StringValue containing the relative path of the generated PDF file.

Return type:

StringValue

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

Generate a list of texts.

Parameters:

nb – Number of texts to generate.

Returns:

List of texts.

Return type:

List[str]

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. Defaults to (100, 100).

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

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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, extension: str | None = None) StringValue[source]

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

Parameters:
  • size – Tuple of width and height of the image in pixels. Defaults to (100, 100).

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

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • extension – File extension. Defaults to None, in which case the image_format value is used.

Returns:

StringValue containing the relative path of the generated TIF file.

Return type:

StringValue

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

Generate a random time string formatted according to fmt.

Parameters:

fmt – The format to use. Defaults to %H:%M:%S.

Returns:

A random time string formatted according to fmt.

Return type:

str

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

Generate a random TLD.

Parameters:

tlds – List of TLDs to use. If not given or None, a default list of TLDs is used.

Returns:

TLD.

Return type:

str

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

Create a text document file.

Parameters:
  • nb_chars – Number of characters in the text file. Defaults to 200.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • text – Text content to write to the file. If None, random text will be generated. Can also be a StringTemplate or LazyStringTemplate. Defaults to None.

Returns:

StringValue containing the relative path of the generated text file.

Return type:

StringValue

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

Generate a random URL.

Example without params:

FAKER.url()

Example with params:

FAKER.url(
    protocols=("https",),
    tlds=("com",),
    suffixes=(".py",),
)
Parameters:
  • protocols – List of protocols to use. If not given or None, default protocols are used.

  • tlds – List of TLDs to use. If not given or None, default TLDs are used.

  • suffixes – List of suffixes to use. If not given or None, default suffixes are used.

Returns:

URL.

Return type:

str

username() str[source]

Generate a username.

Returns:

Username.

Return type:

str

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

Generate a list of usernames.

Parameters:

nb – Number of usernames to generate.

Returns:

List of usernames.

Return type:

List[str]

uuid() UUID[source]

Generate a UUID.

Returns:

UUID

Return type:

UUID

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

Generate a list of UUIDs.

Parameters:

nb – Number of UUIDs to generate.

Returns:

List of UUIDs

Return type:

List[UUID]

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

Create a WAV audio.

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

  • duration – Duration of the tone in seconds. Defaults to 1.

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

  • sample_rate – Sampling rate in Hz. Defaults to 44100.

Returns:

Byte content of the WAV audio.

Return type:

bytes

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

Create a WAV audio file.

Parameters:
  • frequency – Frequency of the audio in Hertz. Defaults to 440.

  • duration – Duration of the audio in seconds. Defaults to 1.

  • volume – Volume of the audio (0.0 to 1.0). Defaults to 0.5.

  • sample_rate – Sample rate of the audio in samples per second. Defaults to 44100.

  • storage – Storage backend to use. Defaults to None, in which case FileSystemStorage is used.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

Returns:

StringValue containing the relative path of the generated WAV file.

Return type:

StringValue

word() str[source]

Generate a word.

Returns:

Word.

Return type:

str

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

Generate a list of words.

Parameters:

nb – Number of words to generate.

Returns:

List of words.

Return type:

List[str]

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. Defaults to 1900.

  • end_year – The upper bound for the random year. Defaults to 2100.

Returns:

A random year as an integer.

Return type:

int

zip(options: Dict[str, Any] | None = 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: MetaData | None = None, storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, options: Dict[str, Any] | None = 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: StringValue | str) bool[source]
search(value: str) StringValue | None[source]
class fake.FileSystemStorage(root_path: str | Path | None = '/tmp', rel_path: str | None = '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: str | None = None, basename: str | None = 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: str | None = 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: int | None = None, faker: Faker | None = 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: str | List[str]) None[source]
content: str | None
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: int | None = None, texts: List[str] | None = None, metadata: MetaData | None = 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.RtfGenerator(faker: Faker)[source]

Bases: object

RtfGenerator - generates an RTF file with text.

Usage example:

from pathlib import Path
from fake import FAKER

Path("/tmp/example.rtf").write_bytes(
    RtfGenerator(FAKER).create(nb_pages=5)
)
create(nb_pages: int | None = None, texts: List[str] | None = None, metadata: MetaData | None = None) bytes[source]
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: int | None = None, faker: Faker | None = 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.TestCLI(methodName='runTest')[source]

Bases: TestCase

setUp()[source]

Hook method for setting up the test fixture before exercising it.

test_date_provider()[source]
test_date_provider_with_args()[source]
test_docx_file_provider()[source]
test_generic_file_provider()[source]
test_no_command()[source]
test_provider_list()[source]
test_pyint_provider()[source]
class fake.TestFaker(methodName='runTest')[source]

Bases: TestCase

classmethod is_valid_email(email: str) bool[source]
setUp() None[source]

Hook method for setting up the test fixture before exercising it.

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

test_authorship_data()[source]

Test AuthorshipData.

test_bin() None[source]
test_bin_file() None[source]
test_bmp() None[source]
test_bmp_file() None[source]
test_city()[source]
test_clean_up_exceptions()[source]
test_company_email() None[source]
test_company_email_custom_domain_names() None[source]
test_company_emails() None[source]
test_country()[source]
test_country_code()[source]
test_create_inner_bmp_file()[source]
test_create_inner_docx_file()[source]
test_create_inner_eml_file()[source]
test_create_inner_eml_file_with_options()[source]
test_create_inner_eml_file_with_options_list_create()[source]
test_create_inner_epub_file()[source]
test_create_inner_generic_file_with_lazy_string_template_and_dir_path()[source]

create_inner_generic_file with LazyStringTemplate content and dir_path produces independently rendered files at the correct in-archive path.

test_create_inner_gif_file()[source]
test_create_inner_jpg_file()[source]
test_create_inner_odt_file()[source]
test_create_inner_pdf_file()[source]
test_create_inner_png_file()[source]
test_create_inner_ppm_file()[source]
test_create_inner_rtf_file()[source]
test_create_inner_svg_file()[source]
test_create_inner_tar_file()[source]
test_create_inner_tar_file_with_options()[source]
test_create_inner_tar_file_with_options_list_create()[source]
test_create_inner_text_pdf_file()[source]
test_create_inner_tif_file()[source]
test_create_inner_txt_file()[source]
test_create_inner_wav_file()[source]
test_create_inner_zip_file()[source]
test_create_inner_zip_file_with_options()[source]
test_create_inner_zip_file_with_options_list_create()[source]
test_date() None[source]
test_date_deprecated_units() None[source]

Test deprecated H and M units still work but emit warnings.

test_date_iso_range() None[source]

Test ISO date format support.

test_date_relative_months() None[source]

Test months unit.

test_date_relative_weeks() None[source]

Test weeks unit.

test_date_relative_years() None[source]

Test years unit.

test_date_time() None[source]
test_date_time_iso_range() None[source]

Test ISO datetime format with time component.

test_date_time_relative_months() None[source]

Test months unit for datetime.

test_date_time_relative_weeks() None[source]

Test weeks unit for datetime.

test_date_time_relative_years() None[source]

Test years unit for datetime.

test_dir_path() None[source]
test_docx() None[source]
test_docx_file() None[source]
test_domain_name_custom_domain_names() None[source]
test_domain_name_with_defaults() None[source]
test_email() None[source]
test_email_custom_domain_names() None[source]
test_emails() None[source]
test_eml() None[source]
test_eml_file() None[source]
test_epub() None[source]
test_factory_method() None[source]

Test FactoryMethod.

test_factory_methods() None[source]
test_faker_init() None[source]
test_file_extension() None[source]
test_file_name() None[source]
test_file_path() None[source]
test_first_name() None[source]
test_first_names() None[source]
test_free_email() None[source]
test_free_email_domain()[source]
test_free_emails() None[source]
test_generic_file() None[source]
test_generic_file_accepts_lazy_string_template()[source]

generic_file renders a LazyStringTemplate fresh on each call.

test_generic_file_accepts_string_template()[source]

generic_file renders a StringTemplate before writing.

test_generic_file_basename_absolute_path()[source]

generic_file rejects absolute path in basename.

test_generic_file_basename_invalid_chars()[source]

generic_file rejects invalid characters in basename.

test_generic_file_basename_lazy_string_template()[source]

generic_file accepts LazyStringTemplate as basename.

test_generic_file_basename_path_traversal()[source]

generic_file rejects path traversal in basename.

test_generic_file_basename_string_template()[source]

generic_file accepts StringTemplate as basename.

test_generic_file_prefix_absolute_path()[source]

generic_file rejects absolute path in prefix.

test_generic_file_prefix_invalid_chars()[source]

generic_file rejects invalid characters in prefix.

test_generic_file_prefix_lazy_string_template()[source]

generic_file accepts LazyStringTemplate as prefix.

test_generic_file_prefix_path_traversal()[source]

generic_file rejects path traversal in prefix.

test_generic_file_prefix_string_template()[source]

generic_file accepts StringTemplate as prefix.

test_geo_location()[source]
test_get_by_alias() None[source]
test_get_by_uid() None[source]
test_gif() None[source]
test_gif_file() None[source]
test_graphic_pdf() None[source]
test_iban()[source]
test_image()[source]
test_image_url() None[source]
test_ipv4() None[source]
test_isbn10()[source]
test_isbn13()[source]
test_isbn13_checksum()[source]
test_jpg() None[source]
test_jpg_file() None[source]
test_last_name() None[source]
test_last_names() None[source]
test_latitude()[source]

Test that the latitude function returns a valid latitude.

test_latitude_longitude()[source]

Test that the latlng returns a valid (latitude, longitude) pair.

test_lazy_string_template() None[source]
test_locale()[source]
test_longitude()[source]

Test that the longitude function returns a valid longitude.

test_metadata() None[source]

Test MetaData.

test_mime_type() None[source]
test_name() None[source]
test_names() None[source]
test_odt() None[source]
test_odt_file() None[source]
test_paragraph() None[source]
test_paragraphs() None[source]
test_parse_date_string() None[source]
test_password()[source]

Test password.

test_pdf_file() None[source]
test_pdf_file_basename_string_template()[source]

pdf_file accepts StringTemplate as basename.

test_pdf_file_basename_validation()[source]

pdf_file validates basename.

test_pdf_file_prefix_lazy_string_template()[source]

pdf_file accepts LazyStringTemplate as prefix.

test_png() None[source]
test_png_file() None[source]
test_ppm() None[source]
test_ppm_file() None[source]
test_pybool() None[source]
test_pydecimal()[source]
test_pyfloat() None[source]
test_pyint() None[source]
test_pystr() None[source]
test_random_choice() None[source]
test_random_sample() None[source]
test_randomise_string()[source]
test_registry_integration() None[source]

Test add.

test_remove_by_string_not_found()[source]
test_remove_exceptions()[source]
test_rtf() None[source]
test_seed() None[source]
test_sentence() None[source]
test_sentences() None[source]
test_slug() None[source]
test_slugs() None[source]
test_storage() None[source]
test_storage_integration() None[source]
test_string_template() None[source]
test_sub_factory() None[source]

Test FACTORY and SubFactory.

test_svg() None[source]
test_svg_file() None[source]
test_tar() None[source]
test_tar_dir_path_literal()[source]

Same guarantee holds for tar().

test_tar_file() None[source]
test_text() None[source]
test_text_pdf() None[source]
test_text_pdf_file() None[source]
test_texts() None[source]
test_tif() None[source]
test_tif_file() None[source]
test_time() None[source]
test_tld_with_custom_tlds() None[source]
test_tld_with_defaults() None[source]
test_txt_file() None[source]
test_txt_file_basename_string_template()[source]

txt_file accepts StringTemplate as basename.

test_txt_file_prefix_lazy_string_template()[source]

txt_file accepts LazyStringTemplate as prefix.

test_txt_file_prefix_validation()[source]

txt_file validates prefix.

test_url() None[source]
test_username() None[source]
test_usernames() None[source]
test_uuid() None[source]
test_uuids() None[source]
test_wav() None[source]
test_wav_file() None[source]
test_word() None[source]
test_words() None[source]
test_year() None[source]

Test that the default year is between 1900 and 2100.

test_zip() None[source]
test_zip_dir_path_literal()[source]

dir_path as a literal string places the file at that subpath.

test_zip_dir_path_sanitization()[source]

dir_path with unsafe paths like .., absolute paths, drive letters.

test_zip_dir_path_template()[source]

dir_path as a string_template expression is resolved before use.

test_zip_file() None[source]
test_zip_without_dir_path_unaffected()[source]

Existing callers that omit dir_path behave exactly as before.

class fake.TestLazyStringTemplate(methodName='runTest')[source]

Bases: TestCase

setUp()[source]

Hook method for setting up the test fixture before exercising it.

test_argument_parsing_error_raises_value_error()[source]
test_complex_argument_parsing()[source]
test_escape_braces()[source]
test_method_call_error_raises_value_error()[source]
test_missing_method_raises_attribute_error()[source]
test_multiple_placeholders()[source]
test_nested_placeholders()[source]
test_no_placeholders()[source]
test_no_wrapping_when_not_specified()[source]
test_placeholder_with_arguments()[source]
test_placeholder_with_boolean_arguments()[source]
test_placeholder_with_empty_arguments()[source]
test_placeholder_with_no_parentheses()[source]
test_placeholder_with_numeric_method_name()[source]
test_placeholder_with_spaces_in_arguments()[source]
test_placeholder_with_underscores_in_method_name()[source]
test_repr_method()[source]
test_simple_placeholder_replacement()[source]
test_str_method()[source]
test_wrapping_functionality()[source]
class fake.TestOrganiseProviders(methodName='runTest')[source]

Bases: TestCase

setUp()[source]

Hook method for setting up the test fixture before exercising it.

test_organise_providers_category_sorting()[source]
test_organise_providers_empty()[source]
test_organise_providers_multiple_providers()[source]
test_organise_providers_multiple_tags()[source]
test_organise_providers_single_tag()[source]
test_organise_providers_sorting()[source]
class fake.TestScript(methodName='runTest')[source]

Bases: TestCase

test_main()[source]
class fake.TestSlugify(methodName='runTest')[source]

Bases: TestCase

test_slugify_empty_string()[source]

Test slugify with an empty string.

test_slugify_mixed_characters()[source]

Test slugify with a mix of alphanumeric and special characters.

test_slugify_non_english_characters()[source]

Test slugify with non-English characters.

test_slugify_numbers()[source]

Test slugify with numbers in the string.

test_slugify_simple()[source]

Test slugify with a simple alphanumeric string.

test_slugify_spaces()[source]

Test slugify with spaces.

test_slugify_special_characters()[source]

Test slugify with special characters.

class fake.TestStringTemplate(methodName='runTest')[source]

Bases: TestCase

setUp()[source]

Hook method for setting up the test fixture before exercising it.

test_argument_parsing_error_raises_value_error()[source]
test_complex_argument_parsing()[source]
test_escape_braces()[source]
test_instance_is_str()[source]
test_join_with_no_templates()[source]
test_join_with_single_template()[source]
test_join_with_string_template()[source]
test_large_number_of_placeholders()[source]
test_method_call_error_raises_value_error()[source]
test_missing_method_raises_attribute_error()[source]
test_multiple_placeholders()[source]
test_nested_placeholders()[source]
test_no_placeholders()[source]
test_no_wrapping_when_not_specified()[source]
test_placeholder_with_arguments()[source]
test_placeholder_with_boolean_arguments()[source]
test_placeholder_with_empty_arguments()[source]
test_placeholder_with_no_parentheses()[source]
test_placeholder_with_numeric_method_name()[source]
test_placeholder_with_spaces_in_arguments()[source]
test_placeholder_with_underscores_in_method_name()[source]
test_repr_method()[source]
test_simple_placeholder_replacement()[source]
test_str_method()[source]
test_wrapping_functionality()[source]
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: int | None = None, texts: List[str] | None = None, metadata: MetaData | None = 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: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, size: Tuple[int, int] = (100, 100), color: Tuple[int, int, int] = (0, 0, 255), dir_path: str | None = None, **kwargs) StringValue[source]

Create inner BMP file.

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

Create inner DOCX file.

fake.create_inner_eml_file(storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, options: Dict[str, Any] | None = None, content: str | None = None, subject: str | None = None, cte_type: str | None = None, policy: Policy | None = None, metadata: MetaData | None = None, dir_path: str | None = None, **kwargs) StringValue[source]

Create inner EML file.

fake.create_inner_generic_file(storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, content: bytes | str | StringTemplate | LazyStringTemplate = '', extension: str = 'txt', dir_path: str | None = None, **kwargs) StringValue[source]

Create an inner file of any format with arbitrary content.

Unlike the other create_inner_* functions which each target a specific file format, this function accepts any extension and any content — including a StringTemplate or LazyStringTemplate, which is rendered fresh on each call.

Usage examples:

# Plain string content
create_inner_generic_file(
    content="<root/>",
    extension="xml",
)

# StringTemplate — rendered once at call-site construction time
create_inner_generic_file(
    content=StringTemplate("<title>{sentence(nb_words=4)}</title>"),
    extension="xml",
)

# LazyStringTemplate — rendered fresh on every call, useful with
# count > 1 so each file gets independently generated content
create_inner_generic_file(
    content=LazyStringTemplate("<title>{sentence(nb_words=4)}</title>"),
    extension="xml",
    dir_path="{dir_path(depth=2)}",
)
Parameters:
  • storage – Storage backend to use. Defaults to FileSystemStorage.

  • basename – Base name for the file. Defaults to None.

  • prefix – Prefix for the file name. Defaults to None.

  • content – File content. Accepts bytes, str, StringTemplate, or LazyStringTemplate. Defaults to "".

  • extension – File extension without leading dot. Defaults to "txt".

  • dir_path – Optional in-archive subdirectory. Resolved through FAKER.string_template() so template expressions such as "{dir_path(depth=3)}" are supported. Defaults to None.

  • **kwargs

    Reserved for API compatibility. Currently ignored.

Returns:

StringValue containing the relative path of the generated file.

Return type:

StringValue

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

Create inner GIF file.

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

Create inner JPG file.

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

Create inner ODT file.

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

Create inner PDF file.

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

Create inner PNG file.

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

Create inner PPM file.

fake.create_inner_rtf_file(storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, nb_pages: int | None = 1, texts: List[str] | None = None, metadata: MetaData | None = None, dir_path: str | None = None, **kwargs) StringValue[source]

Create inner RTF file.

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

Create inner SVG file.

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

Create inner TAR file.

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

Create inner text PDF file.

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

Create inner TIF file.

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

Create inner TXT file.

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

Create inner WAV file.

fake.create_inner_zip_file(storage: BaseStorage | None = None, basename: str | StringTemplate | LazyStringTemplate | None = None, prefix: str | StringTemplate | LazyStringTemplate | None = None, options: Dict[str, Any] | None = None, metadata: MetaData | None = None, dir_path: str | None = 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.organise_providers(provider_tags) Dict[str, Any][source]

Organise 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: Tuple[str, ...] | None = None) Callable[source]
fake.resolve_inner_directory(file: StringValue, directory: str) Path[source]

Resolve the in-archive path for an inner file.

Combines three components:

  1. directory — the static options["directory"] prefix supplied by the caller of zip() / tar().

  2. file.data.get("directory", "") — an optional subdirectory set by the creator function via its dir_path parameter.

  3. Path(file).name — the bare filename of the generated file, derived from the real on-disk path as always.

When data["directory"] is absent (i.e. dir_path was not passed to the creator), this returns the same result as the current Path(directory) / Path(file).name expression, preserving full backwards compatibility.

Parameters:
  • file – The StringValue returned by a creator function.

  • directory – The options["directory"] prefix (may be "").

Returns:

The resolved in-archive path.

Return type:

Path

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)