faker Documentation

Faker is a Python package that generates fake data for you.

RAW Doc

1. Project Overview & Quickstart (joke2k/faker)

File: docs/includes/substitutions.rst

.. |strftime| replace::
:meth:strftime() <datetime.datetime.strftime>

.. |random_sample| replace::
:meth:random_sample() <faker.providers.BaseProvider.random_sample>

.. |random_choices| replace::
:meth:random_choices() <faker.providers.BaseProvider.random_choices>

.. |randomize_nb_elements| replace::
:meth:randomize_nb_elements() <faker.providers.BaseProvider.randomize_nb_elements>

.. |swift| replace::
:meth:swift() <faker.providers.bank.Provider.swift>

.. |ean| replace::
:meth:ean() <faker.providers.barcode.Provider.ean>

.. |ean13| replace::
:meth:ean13() <faker.providers.barcode.Provider.ean13>

.. |localized_ean| replace::
:meth:localized_ean() <faker.providers.barcode.Provider.localized_ean>

.. |EnUsBarcodeProvider.ean13| replace::
:meth:EnUsBarcodeProvider.ean13() <faker.providers.barcode.en_US.Provider.ean13>

.. |EnUsBarcodeProvider.upc_a| replace::
:meth:EnUsBarcodeProvider.upc_a() <faker.providers.barcode.en_US.Provider.upc_a>

.. |EnUsBarcodeProvider.upc_e| replace::
:meth:EnUsBarcodeProvider.upc_e() <faker.providers.barcode.en_US.Provider.upc_e>

.. |date_time_between| replace::
:meth:date_time_between() <faker.providers.date_time.Provider.date_time_between>

.. |file_name| replace::
:meth:file_name() <faker.providers.file.Provider.file_name>

.. |file_extension| replace::
:meth:file_extension() <faker.providers.file.Provider.file_extension>

.. |unix_device| replace::
:meth:unix_device() <faker.providers.file.Provider.unix_device>

.. |word| replace::
:meth:word() <faker.providers.lorem.Provider.word>

.. |words| replace::
:meth:words() <faker.providers.lorem.Provider.words>

.. |sentence| replace::
:meth:sentence() <faker.providers.lorem.Provider.sentence>

.. |sentences| replace::
:meth:sentences() <faker.providers.lorem.Provider.sentences>

.. |paragraph| replace::
:meth:paragraph() <faker.providers.lorem.Provider.paragraph>

.. |paragraphs| replace::
:meth:paragraphs() <faker.providers.lorem.Provider.paragraphs>

.. |text| replace::
:meth:text() <faker.providers.lorem.Provider.text>


File: docs/coding_style.rst

Coding Style

We use the black code style with a line length of 120 characters and trailing commas.

You can format the code with::

text
black --line-length 120

Please include type hints_ for every provider method you write. An overview of generic types is included below.

You can find our complete flake8 configuration in the tox.ini_ file.

Use is instead of == when comparing a variable to None, False, or True (see https://www.flake8rules.com/rules/E711.html)::

text
if my_var is None:
    ...  # do something

Data Sets

For each data set, please provide a comment with reference to the source
and/or origin of the data. If the source is a wiki, please also include the date and time it was last checked.

We only accept new data if it's coming from statistical sources, such as census or government institutions.
This includes names and their distribution.

You may include multiple sources, but each name must come from a source. We will not accept names authored
exclusively by contributors.

Name Lists

When you have long lists of names, please order them alphabetically. Keep the lines length as close as
possible to 120 characters, without exceeding the limit.

Type Hints

typing.py includes generic types that can be re-used throughout the codebase. Moreover, some type definitions are
included in other parts of the code. If you add a generic type, please specify its usage below:

.. list-table:: Title
:widths: 15 60
:header-rows: 1

    • Type
    • Used for
    • providers.ElementsType
    • When creating a variable in a Provider (e.g. for a specific locale), which is not defined in the superclass, self.random_element(), self.random_elements(), self.random_choices() and self.random_sample() assume this to be the input format.
    • typing.DateParseType
    • Input for various faker.providers.date_time functions that parse (relative) dates/times.
    • typing.HueType
    • Hue name, float value or integer range.
    • typing.GenderType
    • String variable that can only have values "F" (female) and "M" (male)

Tests

Please add tests for all new providers.

When adding a new test class, please find its place in alphabetical order.

.. _tox.ini: https://github.com/joke2k/faker/blob/master/tox.ini
.. _pep 8: https://python.org/dev/peps/pep-0008
.. _pep 263: https://python.org/dev/peps/pep-0263
.. _type hints: https://docs.python.org/3/library/typing.html


File: docs/communityproviders.rst

.. ref-communityproviders:

Community Providers

Here's a list of Providers written by the community:

+---------------+---------------------------+----------------------------------+
| Provider name | Description | URL |
+===============+===========================+==================================+
| AI Provider | Fake data for AI/ML | faker-ai-provider_ |
| | models, companies, and | |
| | datasets. | |
+---------------+---------------------------+----------------------------------+
| Airtravel | Airport names, airport | faker_airtravel_ |
| | codes, and flights. | |
+---------------+---------------------------+----------------------------------+
| Biology | Fake data from biology | faker_biology_ |
| | and life-science domains | |
| | for testing purposes | |
+---------------+---------------------------+----------------------------------+
| Credit Score | Fake credit score data | faker_credit_score_ |
| | for testing purposes | |
+---------------+---------------------------+----------------------------------+
| Datasets | Build providers based | faker-datasets_ |
| | on datasets | |
+---------------+---------------------------+----------------------------------+
| Ecommerce | Fake data for e-commerce | faker-ecommerce-provider_ |
| | e.g. products, orders | |
+---------------+---------------------------+----------------------------------+
| Education | Public school name and | faker_education_ |
| | info for testing purposes | |
+---------------+---------------------------+----------------------------------+
| Faker File | Generate files with fake | faker-file_ |
| | content | |
+---------------+---------------------------+----------------------------------+
| Geoscience | Earth sciences-related | faker_geoscience_ |
| | fake-random data | |
| | generators. | |
+---------------+---------------------------+----------------------------------+
| Healthcare | Multi-language medical | faker_healthcare_ |
| | data: diseases, ICD-10, | |
| | medications, and more. | |
+---------------+---------------------------+----------------------------------+
| Market Data | Fake market data | |
| | identifiers (SEDOL, CUSIP,| faker_marketdata_ |
| | ISIN, etc.) | |
| | | |
+---------------+---------------------------+----------------------------------+
| Microservice | Fake microservice names | faker_microservice_ |
+---------------+---------------------------+----------------------------------+
| Music | Music genres, subgenres, | faker_music_ |
| | and instruments. | |
+---------------+---------------------------+----------------------------------+
| Observability | Fake logs, correlated | faker-observability-provider_ |
| | OpenTelemetry-style | |
| | traces, and k8s metadata. | |
+---------------+---------------------------+----------------------------------+
| Posts | Fake posts in markdown | mdgen_ |
| | format | |
+---------------+---------------------------+----------------------------------+
| PySpark | Fake PySpark DataFrame | faker_pyspark_ |
| | and Schema generator | |
+---------------+---------------------------+----------------------------------+
| Vehicle | Fake vehicle information | faker_vehicle_ |
| | includes Year Make Model | |
+---------------+---------------------------+----------------------------------+
| WebProvider | Web-related data such as | faker_web_ |
| | mime-type and web server | |
| | versions. | |
+---------------+---------------------------+----------------------------------+
| Wi-Fi ESSID | Fake Wi-Fi ESSIDs. | faker_wifi_essid_ |
+---------------+---------------------------+----------------------------------+
| Optional | Small wrapper around | optional_faker_ |
| | faker, to make values | |
| | optional! | |
+---------------+---------------------------+----------------------------------+
| Presidio | Create synthetic datasets | presidio-evaluator_ |
| Sentence | for training Named Entity | |
| Faker | Recognition models | |
| | using Faker. | |
+---------------+---------------------------+----------------------------------+
| Security | Fake data related to | faker-security_ |
| | security e.g. CVSS, CVE | |
+---------------+---------------------------+----------------------------------+
| Scientific | Fake author identifiers | faker_researcher_ids_ |
| | for scientific databases | |
| | (Scopus, ORCID etc.) | |
+---------------+---------------------------+----------------------------------+
| Sci Fi | Fake science fiction | faker-galactic_ |
| | themed data from popular | |
| | sci-fi universes | |
+---------------+---------------------------+----------------------------------+

If you want to add your own provider to this list, please submit a Pull Request to our repo_.

In order to be included, your provider must satisfy these requirements:

  • it must have tests.
  • it must be published on PyPI.
  • it must have an OSI-Approved_ License.
  • it must not duplicate any functionality already present in Faker.
  • it must not contain any profanity, either in code or in documentation.
  • it must not contain any malicious nor any kind of telemetry code.

.. _repo: https://github.com/joke2k/faker/
.. _faker_pk: https://pypi.org/project/faker-pk/
.. _OSI-Approved: https://opensource.org/licenses/alphabetical
.. _faker-ai-provider: https://pypi.org/project/faker-ai-provider/
.. _faker_airtravel: https://pypi.org/project/faker_airtravel/
.. _faker_biology: https://pypi.org/project/faker_biology/
.. _faker_credit_score: https://pypi.org/project/faker-credit-score/
.. _faker-datasets: https://pypi.org/project/faker-datasets/
.. _faker_education: https://pypi.org/project/faker_education/
.. _faker-ecommerce-provider: https://pypi.org/project/faker-ecommerce-provider/
.. _faker-file: https://pypi.org/project/faker-file/
.. _faker_geoscience: https://pypi.org/project/faker-geoscience/
.. _faker_healthcare: https://pypi.org/project/faker-healthcare-provider/
.. _faker_marketdata: https://pypi.org/project/faker-marketdata/
.. _faker_microservice: https://pypi.org/project/faker-microservice/
.. _faker_music: https://pypi.org/project/faker_music/
.. _faker-observability-provider: https://pypi.org/project/faker-observability-provider/
.. _mdgen: https://pypi.org/project/mdgen/
.. _faker_pyspark: https://pypi.org/project/faker-pyspark/
.. _faker_vehicle: https://pypi.org/project/faker-vehicle/
.. _faker_web: https://pypi.org/project/faker_web/
.. _faker_wifi_essid: https://pypi.org/project/faker-wifi-essid/
.. _optional_faker: https://pypi.org/project/optional_faker
.. _presidio-evaluator: https://pypi.org/project/presidio-evaluator
.. _faker-security: https://pypi.org/project/faker-security/
.. _faker_researcher_ids: https://pypi.org/project/faker-researcher-ids/
.. _faker-galactic: https://pypi.org/project/faker-galactic/


File: docs/fakerclass.rst

Using the Faker Class

In version 2.0.4 and below, the Faker object is just a shortcut for the class method
Factory.create, and that method creates a Generator object with access to the wide
selection of provider methods. Because of how everything was set up, it was difficult to do
certain things without going through the Factory and Generator internals and without
potentially breaking a lot of things that will be difficult for users to fix when they upgrade.

The solution was to introduce a new Faker proxy class that will, for the most part, behave
just like the old Faker shortcut but with support for multiple locales while providing the
option to subclass and a very simple upgrade path should old code be affected. For the purposes
of this document, the terms new Faker and old Faker will be used where the former refers
to the new proxy class, and the latter refers to the Factory.create shortcut.

Breaking Change

Any codebase that uses the Faker.seed() method will be affected, because while both old and
new Faker.seed() points to Generator.seed(), in new Faker, invocation of the method
from a Faker object instance has been disabled, and attempting to do so will raise a
TypeError as shown below.

.. code:: python

text
TypeError: Calling `.seed()` on instances is deprecated. Use the class method `Faker.seed()` instead.

The rationale can be found in the relevant PR_, but the goal is to deal with a non-explicit
legacy behavior involving a shared random.Random instance that we believe can only become
more confusing once new Faker is added.

Upgrade Guide

Suppose that the affected code looks something like this:

.. code:: python

text
from faker import Faker
fake = Faker()
fake.seed(0)  # This will raise a TypeError

Just replace all seed() method calls from instances with Faker.seed() as shown below. This
is all that is needed to start using the new Faker class and its features, even if additional
arguments are passed to Faker, because the arguments expected by new Faker and old
Faker are the same.

.. code:: python

text
from faker import Faker
fake = Faker()
Faker.seed(0)

A conservative approach is to redefine Faker as the old shortcut shown below. This will skip
using the new proxy class, but the code will still be able to use any new provider methods moving
forward while being unaffected by new bugs. Of course, that also means there will be no multiple
locale support and no option to subclass.

.. code:: python

text
from faker.factory import Factory
Faker = Factory.create
fake = Faker()
fake.seed(0)

Proxy Class Implementation Details

A new Faker instance is just a proxy object that has references to Generator objects,
one for each unique locale specified at instantiation. Those Generator objects are just
"instances" of old Faker. If there is only one internal Generator object, the new
Faker instance is running in single locale mode. If there is more than one, then it is
running in multiple locale mode.

In single locale mode, a new Faker instance can easily be forced to behave like an instance
created using old Faker, because a similar interface can be exposed on the new Faker
instance, and then proxy calls to methods, properties, and attributes to the sole Generator
object in a 1:1 fashion. In fact, that is how it is implemented and how backwards compatibility
was preserved (save for Faker.seed).

In multiple locale mode, however, that 1:1 mapping is no longer present, and how calls are proxied
depends on whether the attribute is a provider method or some attribute present in Generator
objects. It is possible to provide sane default implementations that will map neatly like what
we did for seed_instance, but the rest like add_provider and the random getter and setter
are more dependent on specific use cases or are potentially dangerous.

In those cases, it is better for users to create their own subclass with their implementation or to
directly call those methods from the internal Generator objects themselves. Multiple locale mode
will be discussed in more detail in its dedicated section_.

Proxy Class Attribute Name Resolution

The proxy class has a fairly involved attribute name resolution behavior that runs in this order:

  1. If the attribute name is seed, raise a TypeError. This prevents the class method seed
    from being called from an instance.
  2. If #1 does not apply, check if the attribute name matches an attribute present in the proxy
    class instance. If there is one, return the matching attribute.
  3. If #2 failed, check if the instance is in single locale mode. If yes, proxy the call to the
    sole internal Generator object, and attempt to return a matching attribute.
  4. If #3 does not apply, the instance is henceforth known to be in multiple locale mode. Proceed
    by checking if the attribute name matches a Generator attribute. If it does, raise a
    NotImplementedError.
  5. If #4 does not apply, check if the attribute name matches a cache pattern regex. If it does not,
    raise an AttributeError, since it should already have been handled by #2 if one does exist.
  6. If everything else has failed or does not apply, assume that the attribute name might be
    referring to a provider method and perform factory/generator selection, and proxy the call
    to the selected Generator object.

Factory/generator selection will be discussed in more detail under multiple locale mode's
dedicated section_.

Locale Normalization

Depending on the locale value passed, a new Faker instance will either operate in single
locale mode or multiple locale mode. The value of locale can be one of the following:

  1. Any empty value like None (automatically defaults to en_US)
  2. A valid locale string, underscored or hyphenated
  3. A list, tuple, or set with valid locale strings, underscored or hyphenated
  4. An OrderedDict with key-value pairs of valid locale strings (underscored or
    hyphenated) and weights

The first two are options already expected by old Faker, so it is pretty much the same for new
Faker. Using any of those two options will always result in a new Faker instance that is
in single locale mode. In that mode, there is really no need to retrieve a reference to the
internal Generator object because of the 1:1 proxying behavior discussed earlier.

The potential pitfalls lie in multiple locale mode and when there is a need to access the internal
Generator objects individually. Since locale strings can be written underscored (en_US) or
hyphenated (en-US), this can lead to confusion and errors, so locale strings have to be normalized
to provide consistent results without duplicates.

During instantiation, new Faker will normalize locale strings to the underscore format, and it
will also store them as such. In other words, the locale string en_US will be treated the same
as en-US, and when both are specified, the last to be processed will be treated as a duplicate
and will be discarded. The same normalization is also performed when accessing the internal
Generator object via key index.

For example, the code below will create a new Faker instance that is in single locale mode
even if four locales were specified.

.. code:: python

text
from faker import Faker
fake = Faker(['en-US', 'en_US', 'en_US', 'en-US'])

# Will return ['en_US']
fake.locales

# Get reference to en_US generator
us1 = fake['en_US']

# Get reference to en-US generator
us2 = fake['en-US']

# Will return True
us1 == us2

.. _dedicated section:

Multiple Locale Mode

To enable multiple locale mode, the value of locale argument must be a list, tuple, set, or
OrderedDict with more than one valid locale, post-normalization. For example:

.. code:: python

text
from collections import OrderedDict
from faker import Faker

locale_list = ['en-US', 'ja-JP', 'en_US']
fake1 = Faker(locale_list)

# Will return ['en_US', 'ja_JP']
fake1.locales

locale_odict = OrderedDict([
    ('en-US', 1),
    ('ja-JP', 2),
    ('en_US', 2),
])
fake2 = Faker(locale_odict)

# Will return ['en_US', 'ja_JP']
fake2.locales

In this mode, calling a prospective provider method from the new Faker instance will run
factory/selection logic in this order:

  1. Check if a cached mapping already exists for the provider method. If yes, use that mapping,
    and skip to #3.
  2. If #1 does not apply, check which Generator objects support the provider method. Cache
    the results of the mapping, along with corresponding weights if they were provided during
    instantiation.
  3. If no generator supports the provider method, an AttributeError will be raised just as it
    would have been raised using old Faker.
  4. If there is only one generator that supports the provider method, return the only generator.
  5. If there is more than one applicable generator, and no weights were provided, randomly select
    a generator using a uniform distribution, i.e. random.choice.
  6. If there is more than one applicable generator, and weights were provided, randomly select
    a generator using a distribution defined by the provided weights.

Other than being able to customize probabilities based on locales and minimizing performance
penalties, the factory selection logic guarantees that invoking a provider method will not fail,
for as long as at least there is at least one internal Generator object supports it.

Examples

There are times when it is much easier to show than it is to explain in words, so here is
a cheatsheet for new Faker in multiple locale mode.

.. code:: python

text
from collections import OrderedDict
from faker import Faker
locales = OrderedDict([
    ('en-US', 1),
    ('en-PH', 2),
    ('ja_JP', 3),
])
fake = Faker(locales)

# Get the list of locales specified during instantiation
fake.locales

# Get the list of internal generators of this `Faker` instance
fake.factories

# Get the internal generator for 'en_US' locale
fake['en_US']

# Get the internal generator for 'en_PH' locale
fake['en_PH']

# Get the internal generator for 'ja_JP' locale
fake['ja_JP']

# Will raise a KeyError as 'en_GB' was not included
fake['en_GB']

# Set the seed value of the shared `random.Random` object
# across all internal generators that will ever be created
Faker.seed(0)

# Creates and seeds a unique `random.Random` object for
# each internal generator of this `Faker` instance
fake.seed_instance(0)

# Creates and seeds a unique `random.Random` object for
# the en_US internal generator of this `Faker` instance
fake.seed_locale('en_US', 0)

# Generate a name based on the provided weights
# en_US - 16.67% of the time (1 / (1 + 2 + 3))
# en_PH - 33.33% of the time (2 / (1 + 2 + 3))
# ja_JP - 50.00% of the time (3 / (1 + 2 + 3))
fake.name()

# Generate a name under the en_US locale
fake['en-US'].name()

# Generate a zipcode based on the provided weights
# Note: en_PH does not support the zipcode provider method
# en_US - 25% of the time (1 / (1 + 3))
# ja_JP - 75% of the time (3 / (1 + 3))
fake.zipcode()

# Generate a zipcode under the ja_JP locale
fake['ja_JP'].zipcode()

# Will raise an AttributeError
fake['en_PH'].zipcode()

# Generate a Luzon province name
# Note: only en_PH out of the three supports this provider method
fake.luzon_province()

# Generate a Luzon province name
fake['en_PH'].luzon_province()

# Will raise an AttributeError
fake['ja_JP'].luzon_province()

.. _the relevant PR: https://github.com/joke2k/faker/pull/1052#issuecomment-557170225

Unique Values

New in version v4.2.0 is the .unique attribute on the
Faker proxy.

Accessing provider methods through this attribute guarantees that
the returned values are unique for the lifetime of the Faker instance.

.. code:: python

import faker

fake = faker.Faker()

numbers = set(fake.unique.random_int() for i in range(1000))
assert len(numbers) == 1000

On Faker instances with multiple locales, you can specify the locale to use
for the unique values by using the subscript notation:

.. code:: python

from faker import Faker
fake = Faker(['en_US', 'fr_FR'])
names = [fake.unique["en_US"].first_name() for i in range(500)]
assert len(set(names)) == 500

To clear already seen values, simply call fake.unique.clear(), which will
allow previous values generated to be returned again.

Different argument signatures for provider methods do not share
a uniqueness pool.

.. code:: python

import faker

fake = faker.Faker()

numbers = set(fake.unique.random_int(min=1, max=10) for i in range(10))
other_numbers = set(fake.unique.random_int(min=1, max=5) for i in range(5))

assert other_numbers.issubset(numbers)

If the range of possible values generated by a provider function is small
and the .unique attribute has been used, it's possible that no
suitable unique value will be found after a certain number of iterations.

To avoid infinite loops, at that point, a UniquenessException will
be raised.

.. code:: python

import faker

fake = faker.Faker()

for i in range(3):
fake.unique.boolean() # UniquenessException!

For types with limited value sets (like booleans with only 2 values), you can use
exclude_types() to prevent uniqueness checks for specific types:

.. code:: python

import faker

fake = faker.Faker()

Exclude booleans from uniqueness checks

proxy = fake.unique.exclude_types([bool])

This works fine - booleans can now repeat

for i in range(100):
proxy.pybool() # No UniquenessException!

Other types still enforce uniqueness

names = [proxy.first_name() for i in range(10)]
assert len(set(names)) == 10 # All unique

The exclude_types() method returns a new proxy that shares the same seen values
dictionary, ensuring consistency across different proxy instances:

.. code:: python

from faker import Faker

fake = Faker()

Get a unique name

name1 = fake.unique.first_name()

Create proxy excluding bools

proxy = fake.unique.exclude_types([bool])

This shares the same seen dictionary

name2 = proxy.first_name()
assert name1 != name2 # Still enforces uniqueness for names

As a final caveat, only hashable arguments and return values can be used
with the .unique attribute, as it is backed internally by a set for
fast membership testing.

.. code:: python

import faker

fake = faker.Faker()

fake.unique.profile() # TypeError: unhashable type: 'dict'


File: docs/index.rst

.. Faker documentation master file, created by
sphinx-quickstart on Tue Mar 11 11:25:48 2014.
You can adapt this file completely to your liking, but it should at least
contain the root toctree directive.

Welcome to Faker's documentation!

.. include:: ../README.rst

Contents

.. toctree::
:maxdepth: 2

fakerclass
providers
communityproviders
locales
pytest-fixtures
coding_style
writing-docs

Indices and tables

  • :ref:genindex
  • :ref:modindex
  • :ref:search

File: docs/pytest-fixtures.rst

Pytest Fixtures

Faker includes a faker fixture for pytest.

.. code:: python

def test_faker(faker):
assert isinstance(faker.name(), str)

Out of the box, the faker fixture returns a session-scoped Faker instance to be used across
all tests in your test suite. This instance defaults to the en-US locale, it is reseeded
using a seed value of 0 prior to each test, and the .unique remembered generated values
are cleared.

To change the default locale, you can define a session-scoped autouse faker_session_locale
fixture in your top level conftest.py. To change the default seed value, you define a
session-scoped autouse faker_seed fixture. For example, if you want to use the it_IT
locale and a seed value of 12345, then all you need to do is to include the following in
your top level conftest.py like so:

.. code:: python

import pytest

@pytest.fixture(scope='session', autouse=True)
def faker_session_locale():
return ['it_IT']

@pytest.fixture(scope='session', autouse=True)
def faker_seed():
return 12345

If you need an instance with multiple locale support, then just return a list with multiple, unique,
and valid locales:

.. code:: python

import pytest

@pytest.fixture(scope='session', autouse=True)
def faker_session_locale():
return ['it_IT', 'ja_JP', 'en_US']

Configuration options

As mentioned above, out of the box, a session-scoped Faker instance is returned for your use.
This is done so by design in order to prevent unnecessary Faker instantiations for most use
cases. Of course, there are some uncommon use cases where this approach is insufficient, which is
why the faker fixture is actually a function-scoped fixture that can be configured to behave
differently on demand.

.. important::

Configuring the faker fixture requires some basic understanding of how pytest handles
fixtures (more specifically scoping, sharing, injection). If you are not familiar with the topic,
it is highly recommended to read up on pytest fixtures_ before proceeding.

Locale configuration

text
If a ``faker_locale`` fixture is active for a test, the ``faker`` fixture will fallback to returning
a new ``Faker`` instance for that test (function-scoped), so if you do not like to use the session-scoped
``Faker`` instance, just define and activate a ``faker_locale`` fixture in the appropriate place in
accordance to how ``pytest`` handles fixtures.

For example, if you need to switch to a different locale only for certain tests, you may define an
autouse ``faker_locale`` fixture with a non-session scope in a submodule's ``conftest.py`` or in
the test files themselves like so:

.. code:: python

   import pytest

   @pytest.fixture(scope=any_non_session_scope, autouse=True)
   def faker_locale():
       return ['it_IT']

When the ``faker`` fixture is used in the relevant tests, the fixture will automatically use new
``Faker`` instances:

.. code:: python

   def test_something(faker):
       # The faker fixture here will return a new instance, not the session-scoped instance
       pass

If you want to be more explicit or if you need finer control over which tests should use a new
instance, you may drop ``autouse=True`` and use manual injection:

.. code:: python

   import pytest

   @pytest.fixture()
   def faker_locale():
       return ['it_IT']

   def test_something(faker):
       # The faker fixture will return the session-scoped instance
       pass

   def test_something_else(faker, faker_locale):
       # The faker fixture will return a new instance, not the session-scoped instance
       pass

Seeding configuration

On top of faker_locale, the faker fixture also checks if a faker_seed fixture is active
for a test. If there is none, a seed value of 0 will be used, and if there is one, then the
return value will be used as the seed. The important thing to remember here is this: any test that
uses the faker fixture, whether it returns a session-scoped or a function-scoped Faker
instance, is guaranteed a seeded instance. Seeding is performed independently of the instance
selection logic.

Like briefly mentioned above, defining an autouse session-scoped faker_seed fixture will affect
all relevant tests in the session, but if you want to use a certain seed for a specific set of tests
and just like faker_locale, you will just need to define and activate a faker_seed fixture
in the appropriate place in accordance to how pytest handles fixtures. For example, if you declare
this in a submodule's conftest.py, the faker fixture will return an instance seeded using
12345 for all relevant tests under that submodule.

.. code:: python

import pytest

@pytest.fixture(scope=any_non_session_scope, autouse=True)
def faker_seed():
return 12345

If you want to be more explicit or if you need finer control over which tests should use a different
seed, you may drop autouse=True and use manual injection just as you would for faker_locale:

.. code:: python

import pytest

@pytest.fixture(scope=any_non_session_scope)
def faker_seed():
return 12345

def test_something(faker):
# The faker fixture will use the session seed value
pass

def test_something_else(faker, faker_seed):
# The faker fixture will use the seed value 12345
pass

If you need multiple different seeds for each test, or if you need to reseed halfway inside a test,
you may still explicitly call seed_instance as you normally would with any Faker instance.
Doing so will not affect other tests because of the faker fixture's seeding guarantee.

.. code:: python

Assume the active seed value is 54321 for these tests

def test_something_first(faker):
# The faker fixture, at first, uses seed value 54321
do_thing_a()

text
# Explicit call to seed_instance
   faker.seed_instance(12345)

   # The faker fixture now uses seed value 12345
   do_thing_b()

def test_something_second(faker):
# The faker fixture's seed value is still 54321, not 12345
pass

.. _pytest fixtures: https://docs.pytest.org/en/latest/fixture.html


File: docs/writing-docs.rst

Writing Documentation

Everything under :doc:Standard Providers and :doc:Localized Providers <locales>
is automatically generated using sphinx.ext.autodoc which pulls docstrings from provider
methods during the sphinx-build process. This also means that the docstrings must be written
in valid reStructuredText.

Furthermore, because of the nature of this library, it is imperative to include sample usage to
best demonstrate the capabilities and the possibilities. Since there are so many provider methods
and localized versions, keeping the docs updated would have been a nightmare if the sample usage
section (with reproducible output) of each provider method were to be written by hand.

Automating sample usage sections

To ease the burden of docs maintenance, the project takes advantage of docstring preprocessing offered
by sphinx.ext.autodoc to automatically generate sample usage section, complete with reproducible
output, all from a couple of lines of text using a :sample: "pseudo-role" like so:

.. code-block::

:sample[ size=SIZE][ seed=SEED]:[ KWARGS]

What this will do is generate a sample usage section by calling the provider method SIZE times using
an initial seed value of SEED with optional keyword arguments KWARGS. If no SIZE is specified
or if SIZE is less than 5, it defaults to 5. If no SEED is specified, it defaults to 0.

For example, let us assume that the line :sample: is present in the docstring of a provider method
named method1. That short line of text will automatically generate a sample usage section like this:

.. code-block:: python

Faker.seed(0)
for _ in range(5):
... fake.method1()
...

Output 1

Output 2

Output 3

Output 4

Output 5

Depending on the nature of the provider method, the default of 5 samples may not be enough, so it is
possible to increase that by using size=SIZE. You may also want to supply arguments to change the
behavior of the method, so that can be done using KWARGS. Putting it all together, if we use
:sample size=10: a=1, b=2, c=3, the sample usage section generated will look like this:

.. code-block:: python

Faker.seed(0)
for _ in range(10):
... fake.method1(a=1, b=2, c=3)
...

Output 1

Output 2

Output 3

Output 4

Output 5

Output 6

Output 7

Output 8

Output 9

Output 10

There may also be times when it is desirable to show a particular output, but the pseudo-RNG gets in
the way, e.g. very low chance of said output being generated. To work around this, you may use
seed=SEED to specify an initial seed value that is known to generate the desired output. If we
specify :sample seed=12345: a=2, the sample usage section generated will look like this:

.. code-block:: python

Faker.seed(12345)
for _ in range(5):
... fake.method1(a=2)
...

Output 1

Output 2

Output 3

Output 4

Output 5

You can mix and match SIZE, SEED, and KWARGS, and if KWARGS is becoming too long to
fit a single line, you can break KWARGS into multiple lines in the same way you can break keyword
arguments across multiple lines in actual Python code. For example, let us say the docstring contains
this:

.. code-block:: text

:sample size=25 seed=12345: arg1='very long value, unfortunately',
arg2='yet another long value'

The sample section usage generated will look something like this:

.. code-block:: python

Faker.seed(12345)
for _ in range(25):
... fake.method1(arg1='very long value, unfortunately', arg2='yet another long value')
...

Output 1

Output 2

...

Output 24

Output 25

Docstring preprocessing behavior

If a provider method does not have a docstring or if the docstring does not contain properly
formatted :sample: lines, a default sample usage section will automatically be generated
for the benefit of insufficiently documented provider methods.

A docstring may contain multiple :sample: lines, and all prospective :sample: lines are
first checked to see if they are properly formatted. Malformed instances will be discarded, and
details will be logged to the console as a warning. All properly formatted :sample: lines will
then be removed from the docstring and will undergo sample validation and generation, and the
resulting docstring will have an :examples: section appended to the end. In code form:

.. code-block:: python

Source code docstring

def foo():
"""Summary line

text
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
   Fusce auctor faucibus condimentum.

   :sample:

   Duis posuere lacinia porta.
   Quisque mauris nisl, mattis sed ornare eget, accumsan sit amet mauris.

   :sample size=10 seed=1000:
   """
   return 1

.. code-block:: python

Resulting docstring (more or less) after preprocessing

def foo():
"""Summary line

text
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
   Fusce auctor faucibus condimentum.


   Duis posuere lacinia porta.
   Quisque mauris nisl, mattis sed ornare eget, accumsan sit amet mauris.

   :examples:

   >>> Faker.seed(0)
   >>> for _ in range(5):
   ...     fake.foo()
   ...
   1
   1
   1
   1
   1

   >>> Faker.seed(1000)
   >>> for _ in range(10):
   ...     fake.foo()
   ...
   1
   1
   1
   1
   1
   1
   1
   1
   1
   1
   """
   pass

Notice how it did not remember where the :sample: lines are. Regardless of the original positions
of the :sample: lines, the resulting output of all those lines will be collected and appended
towards the end of the docstring. Please keep this in mind when structuring the flow of docstrings.

There are definitely benefits in allowing sample sections to be generated in place as it make the
creation of richer documentation possible, but unfortunately it is not yet possible due to time
constraints. Until that feature is available, please keep all :sample: lines towards the end
of the docstring to help out the code reviewers.

Sample validation and security segue

Under the hood, the sample sections are generated by feeding the parsed docstring sample lines
into the standard library's eval(). This setup most definitely have some security implications
out of the box, and this is why :sample: lines undergo validation prior to generation.

There are many details behind the validation process, but the long and short of it is that SIZE
and SEED can only be integers, and KWARGS can only be keyword arguments with literal values
or OrderedDict objects. Attempting to do anything else like calling other builtins or even just
performing basic arithmetic will fail the validation. Details of failed validation will be logged
to the console as a warning.

To further improve security, all of the potentially dangerous code used for this purpose have been
isolated into the faker.sphinx module, and this module will be excluded from release distributions
that are hosted in PyPI.

If you are interested in learning more or in performing a security audit on how sample validation is
implemented, please refer to the source code and docstrings of faker.sphinx.validator.SampleCodeValidator
and faker.sphinx.docstring.ProviderMethodDocstring.

Sample generation

Once a :sample: line has been validated, the sphinx-build process will attempt to generate
results based on the information provided. A sample run can still fail if KWARGS contains keyword
arguments that the provider method is not expecting or if executing the provider method results in
an exception. Details of such instances will also be logged to the console as a warning.


File: README.rst

Faker is a Python package that generates fake data for you. Whether
you need to bootstrap your database, create good-looking XML documents,
fill-in your persistence to stress test it, or anonymize data taken from
a production service, Faker is for you.

Faker is heavily inspired by PHP Faker, Perl Faker, and by Ruby Faker_.


::

text
_|_|_|_|          _|
_|        _|_|_|  _|  _|      _|_|    _|  _|_|
_|_|_|  _|    _|  _|_|      _|_|_|_|  _|_|
_|      _|    _|  _|  _|    _|        _|
_|        _|_|_|  _|    _|    _|_|_|  _|

|pypi| |build| |coverage| |license|


Compatibility

Starting from version 4.0.0, Faker dropped support for Python 2 and from version 5.0.0
only supports Python 3.8 and above. If you still need Python 2 compatibility, please install version 3.0.1 in the
meantime, and please consider updating your codebase to support Python 3 so you can enjoy the
latest features Faker has to offer. Please see the extended docs_ for more details, especially
if you are upgrading from version 2.0.4 and below as there might be breaking changes.

This package was also previously called fake-factory which was already deprecated by the end
of 2016, and much has changed since then, so please ensure that your project and its dependencies
do not depend on the old package.

Basic Usage

Install with pip:

.. code:: bash

text
pip install Faker

Use faker.Faker() to create and initialize a faker
generator, which can generate data by accessing properties named after
the type of data you want.

.. code:: python

text
from faker import Faker
fake = Faker()

fake.name()
# 'Lucy Cechtelar'

fake.address()
# '426 Jordy Lodge
#  Cartwrightshire, SC 88120-6700'

fake.text()
# 'Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
#  beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
#  amet quidem. Iusto deleniti cum autem ad quia aperiam.
#  A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui
#  quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur
#  voluptatem sit aliquam. Dolores voluptatum est.
#  Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est.
#  Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati.
#  Et sint et. Ut ducimus quod nemo ab voluptatum.'

Each call to method fake.name() yields a different (random) result.
This is because faker forwards faker.Generator.method_name() calls
to faker.Generator.format(method_name).

.. code:: python

text
for _ in range(10):
  print(fake.name())

# 'Adaline Reichel'
# 'Dr. Santa Prosacco DVM'
# 'Noemy Vandervort V'
# 'Lexi O'Conner'
# 'Gracie Weber'
# 'Roscoe Johns'
# 'Emmett Lebsack'
# 'Keegan Thiel'
# 'Wellington Koelpin II'
# 'Ms. Karley Kiehn V'

Pytest fixtures

Faker also has its own pytest plugin which provides a faker fixture you can use in your
tests. Please check out the pytest fixture docs to learn more.

Providers

Each of the generator properties (like name, address, and
lorem) are called "fake". A faker generator has many of them,
packaged in "providers".

.. code:: python

text
from faker import Faker
from faker.providers import internet

fake = Faker()
fake.add_provider(internet)

print(fake.ipv4_private())

Check the extended docs_ for a list of bundled providers_ and a list of
community providers_.

Localization

faker.Faker can take a locale as an argument, to return localized
data. If no localized provider is found, the factory falls back to the
default LCID string for US english, ie: en_US.

.. code:: python

text
from faker import Faker
fake = Faker('it_IT')
for _ in range(10):
    print(fake.name())

# 'Elda Palumbo'
# 'Pacifico Giordano'
# 'Sig. Avide Guerra'
# 'Yago Amato'
# 'Eustachio Messina'
# 'Dott. Violante Lombardo'
# 'Sig. Alighieri Monti'
# 'Costanzo Costa'
# 'Nazzareno Barbieri'
# 'Max Coppola'

faker.Faker also supports multiple locales. New in v3.0.0.

.. code:: python

text
from faker import Faker
fake = Faker(['it_IT', 'en_US', 'ja_JP'])
for _ in range(10):
    print(fake.name())

# ้ˆดๆœจ ้™ฝไธ€
# Leslie Moreno
# Emma Williams
# ๆธก่พบ ่ฃ•็พŽๅญ
# Marcantonio Galuppi
# Martha Davis
# Kristen Turner
# ไธญๆดฅๅท ๆ˜ฅ้ฆ™
# Ashley Castillo
# ๅฑฑ็”ฐ ๆกƒๅญ

You can check available Faker locales in the source code, under the
providers package. The localization of Faker is an ongoing process, for
which we need your help. Please don't hesitate to create a localized
provider for your own locale and submit a Pull Request (PR).

Optimizations

The Faker constructor takes a performance-related argument called
use_weighting. It specifies whether to attempt to have the frequency
of values match real-world frequencies (e.g. the English name Gary would
be much more frequent than the name Lorimer). If use_weighting is False,
then all items have an equal chance of being selected, and the selection
process is much faster. The default is True.

Command line usage

When installed, you can invoke faker from the command-line:

.. code:: console

text
faker [-h] [--version] [-o output]
      [-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}]
      [-r REPEAT] [-s SEP]
      [-i package.containing.custom_provider]
      [fake] [fake argument [fake argument ...]]

Where:

  • faker: is the script when installed in your environment, in
    development you could use python -m faker instead

  • -h, --help: shows a help message

  • --version: shows the program's version number

  • -o FILENAME: redirects the output to the specified filename

  • -l {bg_BG,cs_CZ,...,zh_CN,zh_TW}: allows use of a localized
    provider

  • -r REPEAT: will generate a specified number of outputs

  • -s SEP: will generate the specified separator after each
    generated output

  • -i package.containing.custom_provider additional custom provider to use. Note this
    is the import path of the package containing your Provider class, not the
    custom Provider class itself. Can be repeated to add multiple providers.

  • fake: is the name of the fake to generate an output for, such as
    name, address, or text

  • [fake argument ...]: optional arguments to pass to the fake (e.g. the
    profile fake takes an optional list of comma separated field names as the
    first argument)

Examples:

.. code:: console

text
$ faker address
968 Bahringer Garden Apt. 722
Kristinaland, NJ 09890

$ faker -l de_DE address
Samira-Niemeier-Allee 56
94812 Biedenkopf

$ faker profile ssn,birthdate
{'ssn': '628-10-1085', 'birthdate': '2008-03-29'}

$ faker -r=3 -s=";" name
Willam Kertzmann;
Josiah Maggio;
Gayla Schmitt;

$ faker -i faker_credit_score credit_score_full
Experian/Fair Isaac Risk Model V2SM
Experian
801

How to create a Provider

.. code:: python

text
from faker import Faker
fake = Faker()

# first, import a similar Provider or use the default one
from faker.providers import BaseProvider

# create new provider class
class MyProvider(BaseProvider):
    def foo(self) -> str:
        return 'bar'

# then add new provider to faker instance
fake.add_provider(MyProvider)

# now you can use:
fake.foo()
# 'bar'

How to create a Dynamic Provider

Dynamic providers can read elements from an external source.

.. code:: python

text
from faker import Faker
from faker.providers import DynamicProvider

medical_professions_provider = DynamicProvider(
     provider_name="medical_profession",
     elements=["dr.", "doctor", "nurse", "surgeon", "clerk"],
)

fake = Faker()

# then add new provider to faker instance
fake.add_provider(medical_professions_provider)

# now you can use:
fake.medical_profession()
# 'dr.'

How to customize the Lorem Provider

You can provide your own sets of words if you don't want to use the
default lorem ipsum one. The following example shows how to do it with a list of words picked from cakeipsum <http://www.cupcakeipsum.com/>__ :

.. code:: python

text
from faker import Faker
fake = Faker()

my_word_list = [
'danish','cheesecake','sugar',
'Lollipop','wafer','Gummies',
'sesame','Jelly','beans',
'pie','bar','Ice','oat' ]

fake.sentence()
# 'Expedita at beatae voluptatibus nulla omnis.'

fake.sentence(ext_word_list=my_word_list)
# 'Oat beans oat Lollipop bar cheesecake.'

How to use with Factory Boy

Factory Boy already ships with integration with Faker. Simply use the
factory.Faker method of factory_boy:

.. code:: python

text
import factory
from myapp.models import Book

class BookFactory(factory.Factory):
    class Meta:
        model = Book

    title = factory.Faker('sentence', nb_words=4)
    author_name = factory.Faker('name')

Accessing the `random` instance

The .random property on the generator returns the instance of
random.Random used to generate the values:

.. code:: python

text
from faker import Faker
fake = Faker()
fake.random
fake.random.getstate()

By default all generators share the same instance of random.Random, which
can be accessed with from faker.generator import random. Using this may
be useful for plugins that want to affect all faker instances.

Unique values

Through use of the .unique property on the generator, you can guarantee
that any generated values are unique for this specific instance.

.. code:: python

from faker import Faker
fake = Faker()
names = [fake.unique.first_name() for i in range(500)]
assert len(set(names)) == len(names)

On Faker instances with multiple locales, you can specify the locale to use
for the unique values by using the subscript notation:

.. code:: python

from faker import Faker
fake = Faker(['en_US', 'fr_FR'])
names = [fake.unique["en_US"].first_name() for i in range(500)]
assert len(set(names)) == len(names)

Calling fake.unique.clear() clears the already seen values.

Note, to avoid infinite loops, after a number of attempts to find a unique
value, Faker will throw a UniquenessException. Beware of the birthday paradox <https://en.wikipedia.org/wiki/Birthday_problem>_, collisions
are more likely than you'd think.

.. code:: python

from faker import Faker

fake = Faker()
for i in range(3):
# Raises a UniquenessException
fake.unique.boolean()

In addition, only hashable arguments and return values can be used
with .unique.

Seeding the Generator

When using Faker for unit testing, you will often want to generate the same
data set. For convenience, the generator also provides a seed() method,
which seeds the shared random number generator. A Seed produces the same result
when the same methods with the same version of faker are called.

.. code:: python

text
from faker import Faker
fake = Faker()
Faker.seed(4321)

print(fake.name())
# 'Margaret Boehm'

Each generator can also be switched to use its own instance of random.Random,
separated from the shared one, by using the seed_instance() method, which acts
the same way. For example:

.. code:: python

text
from faker import Faker
fake = Faker()
fake.seed_instance(4321)

print(fake.name())
# 'Margaret Boehm'

Please note that as we keep updating datasets, results are not guaranteed to be
consistent across patch versions. If you hardcode results in your test, make sure
you pinned the version of Faker down to the patch number.

If you are using pytest, you can seed the faker fixture by defining a faker_seed
fixture. Please check out the pytest fixture docs to learn more.

Tests

Run tests:

.. code:: bash

text
$ tox

Write documentation for the providers of the default locale:

.. code:: bash

text
$ python -m faker > docs.txt

Write documentation for the providers of a specific locale:

.. code:: bash

text
$ python -m faker --lang=de_DE > docs_de.txt

Contribute

Please see CONTRIBUTING_.

License

Faker is released under the MIT License. See the bundled LICENSE_ file
for details.

Credits

  • FZaninotto_ / PHP Faker_
  • Distribute_
  • Buildout_
  • modern-package-template_

.. _FZaninotto: https://github.com/fzaninotto
.. _PHP Faker: https://github.com/fzaninotto/Faker
.. _Perl Faker: https://metacpan.org/dist/Data-Faker
.. _Ruby Faker: https://github.com/stympy/faker
.. _Distribute: https://pypi.org/project/distribute/
.. _Buildout: https://www.buildout.org/
.. _modern-package-template: https://pypi.org/project/modern-package-template/
.. _extended docs: https://faker.readthedocs.io/en/stable/
.. _bundled providers: https://faker.readthedocs.io/en/stable/providers.html
.. _community providers: https://faker.readthedocs.io/en/stable/communityproviders.html
.. _pytest fixture docs: https://faker.readthedocs.io/en/stable/pytest-fixtures.html
.. _LICENSE: https://github.com/joke2k/faker/blob/master/LICENSE.txt
.. _CONTRIBUTING: https://github.com/joke2k/faker/blob/master/CONTRIBUTING.rst
.. _Factory Boy: https://github.com/FactoryBoy/factory_boy

.. |pypi| image:: https://img.shields.io/pypi/v/Faker.svg?style=flat-square&label=version
:target: https://pypi.org/project/Faker/
:alt: Latest version released on PyPI

.. |coverage| image:: https://img.shields.io/coveralls/joke2k/faker/master.svg?style=flat-square
:target: https://coveralls.io/r/joke2k/faker?branch=master
:alt: Test coverage

.. |build| image:: https://github.com/joke2k/faker/actions/workflows/ci.yml/badge.svg
:target: https://github.com/joke2k/faker/actions/workflows/ci.yml
:alt: Build status of the master branch

.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square
:target: https://raw.githubusercontent.com/joke2k/faker/master/LICENSE.txt
:alt: Package license

2. Official Technical Reference & Guides (joke2k/docs)

File: README.md

Laravel Documentation

You can find the online version of the Laravel documentation at https://laravel.com/docs

Contribution Guidelines

If you are submitting documentation for the current stable release, submit it to the corresponding branch. For example, documentation for Laravel 7 would be submitted to the 7.x branch. Documentation intended for the next release of Laravel should be submitted to the master branch.


File: Readme.md

Laravel Documentation

You can find the online version of the Laravel documentation at https://laravel.com/docs

Contribution Guidelines

If you are submitting documentation for the current stable release, submit it to the corresponding branch. For example, documentation for Laravel 7 would be submitted to the 7.x branch. Documentation intended for the next release of Laravel should be submitted to the master branch.


File: readme.md

Laravel Documentation

You can find the online version of the Laravel documentation at https://laravel.com/docs

Contribution Guidelines

If you are submitting documentation for the current stable release, submit it to the corresponding branch. For example, documentation for Laravel 7 would be submitted to the 7.x branch. Documentation intended for the next release of Laravel should be submitted to the master branch.