### Faker CLI Examples Source: https://github.com/xfxf/faker-python/blob/master/README.rst These Bash examples showcase various ways to use the faker command-line interface. They demonstrate generating an address, using a specific locale (German), generating profile data with specific fields (SSN and birthdate), and generating multiple outputs with a custom separator. ```bash $ 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': u'628-10-1085', 'birthdate': '2008-03-29'} $ faker -r=3 -s=";" name Willam Kertzmann ; Josiah Maggio ; Gayla Schmitt ; ``` -------------------------------- ### Install Faker and Generate Docs (Bash) Source: https://github.com/xfxf/faker-python/blob/master/README.rst This command installs the Faker library and redirects its documentation output to a file named 'docs.txt'. It's a straightforward way to generate documentation locally for review or archival. ```bash python -m faker > docs.txt ``` -------------------------------- ### Install Faker Python Package Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst This command installs the Faker package using pip, making it available for use in Python projects. No specific inputs or outputs are associated with this command. ```bash pip install fake-factory ``` -------------------------------- ### Installing Faker Test Dependencies Source: https://github.com/xfxf/faker-python/blob/master/README.rst This Bash command installs the necessary dependencies for running tests for the faker-python project. It reads the list of required packages from the faker/tests/requirements.txt file. ```bash $ pip install -r faker/tests/requirements.txt ``` -------------------------------- ### Generate Multiple Fake Names (Python) Source: https://github.com/xfxf/faker-python/blob/master/README.rst Example showing how to generate a specified number of fake names using a loop. This is useful for populating lists or databases with sample data. ```python from faker import Faker fake = Faker() for _ in range(0,10): print fake.name() ``` -------------------------------- ### Generate Fake Data with Faker (Python) Source: https://github.com/xfxf/faker-python/blob/master/README.rst Basic example demonstrating how to create a Faker generator and use it to generate fake data such as names, addresses, and text. Each method call produces a random, unique result. ```python from faker import Factory fake = Factory.create() 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. ``` ```python from faker import Faker fake = Faker() fake.name() # 'John Doe' ``` -------------------------------- ### Seeding Faker for Reproducible Data Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst This Python example illustrates how to seed the Faker generator using the seed() method. Seeding ensures that the generated fake data is the same every time the script is run, which is particularly useful for unit testing. ```python from faker import Faker fake = Faker() fake.seed(4321) print(fake.name()) ``` -------------------------------- ### Generate Localized Fake Data (Python) Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst Illustrates how to generate fake data in a specific locale using Faker. This example generates Italian names by creating a Faker generator with the 'it_IT' locale. If a locale is not found, it defaults to 'en_US'. ```python from faker import Factory fake = Factory.create('it_IT') for _ in range(0,10): print(fake.name()) # Example Output: # Elda Palumbo # Pacifico Giordano # Sig. Avide Guerra # Yago Amato # Eustachio Messina # Dott. Violante Lombardo # Sig. Alighieri Monti # Costanzo Costa # Nazzareno Barbieri # Max Coppola ``` -------------------------------- ### UTF-8 Encoding Declaration (Python) Source: https://github.com/xfxf/faker-python/blob/master/docs/coding_style.rst Specifies the UTF-8 encoding for Python source files as required by PEP 263. This declaration should be placed on the first or second line of the file to ensure correct character interpretation. ```python # coding=utf-8 ``` -------------------------------- ### Running Faker Tests Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst These bash commands show how to execute the test suite for the faker-python project. Tests can be run using the setup.py script or directly as a Python module. ```bash $ python setup.py test ``` ```bash $ python -m unittest -v faker.tests ``` -------------------------------- ### Running Faker Tests Source: https://github.com/xfxf/faker-python/blob/master/README.rst These Bash commands show two ways to execute the tests for the faker-python library. The first uses the setup.py script, while the second uses the unittest module directly. ```bash $ python setup.py test or $ python -m unittest -v faker.tests ``` -------------------------------- ### Generate Fake Data with Faker (Python) Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst Demonstrates basic usage of the Faker library in Python. It shows how to create a Faker generator and use it to generate fake names, addresses, and text. Each call to a generation method produces a new, random result. ```python from faker import Factory fake = Factory.create() # OR from faker import Faker fake = Faker() print(fake.name()) # 'Lucy Cechtelar' print(fake.address()) # "426 Jordy Lodge # Cartwrightshire, SC 88120-6700" print(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. ``` -------------------------------- ### Creating a Custom Faker Provider Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst This Python snippet demonstrates how to create a custom provider for Faker. It involves defining a class that inherits from BaseProvider and adding methods for custom fake data generation. The new provider is then added to a Faker instance. ```python from faker import Faker from faker.providers import BaseProvider fake = Faker() class MyProvider(BaseProvider): def foo(self): return 'bar' fake.add_provider(MyProvider) print(fake.foo()) ``` -------------------------------- ### Faker CLI Command-Line Usage Source: https://github.com/xfxf/faker-python/blob/master/README.rst This Bash snippet demonstrates how to invoke the faker command-line tool. It includes options for help, version, output file, locale selection, repetition, separator, custom providers, and specifying fake data fields. ```bash faker [-h] [--version] [-o output] [-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}] [-r REPEAT] [-s SEP] [-i {module.containing.custom_provider othermodule.containing.custom_provider}] [fake [fake ...]] ``` -------------------------------- ### Creating a Custom Faker Provider Source: https://github.com/xfxf/faker-python/blob/master/README.rst This Python snippet illustrates how to create a custom provider for the Faker library. It involves importing the Faker instance and BaseProvider, defining a new provider class with custom methods, and then adding this provider to the Faker instance. ```python 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): return 'bar' # then add new provider to faker instance fake.add_provider(MyProvider) # now you can use: fake.foo() > 'bar' ``` -------------------------------- ### Using Faker with Factory-Boy Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst This Python code shows how to integrate Faker with the factory-boy library for generating test data. It defines a Book model and a corresponding factory that uses Faker's lazy attributes to populate model fields like title and author_name. ```python import factory from faker import Factory as FakerFactory from myapp.models import Book faker = FakerFactory.create() class Book(factory.Factory): FACTORY_FOR = Book title = factory.LazyAttribute(lambda x: faker.sentence(nb_words=4)) author_name = factory.LazyAttribute(lambda x: faker.name()) ``` -------------------------------- ### Faker CLI Usage Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst The faker command-line interface allows for generating fake data with various options. It supports specifying locales, output files, repetition counts, separators, and specific fake data fields. ```bash faker [-h] [--version] [-o output] [-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}] [-r REPEAT] [-s SEP] [fake [fake ...]] ``` ```bash $ faker address 968 Bahringer Garden Apt. 722 Kristinaland, NJ 09890 ``` ```bash $ faker -l de_DE address Samira-Niemeier-Allee 56 94812 Biedenkopf ``` ```bash $ faker profile ssn,birthdate {'ssn': u'628-10-1085', 'birthdate': '2008-03-29'} ``` ```bash $ faker -r=3 -s=";" name Willam Kertzmann ; Josiah Maggio ; Gayla Schmitt ; ``` -------------------------------- ### Generate Localized Fake Data with Faker (Python) Source: https://github.com/xfxf/faker-python/blob/master/README.rst Demonstrates how to create a Faker generator for a specific locale (e.g., 'it_IT') to generate localized fake data, such as names. If a locale is not found, it defaults to 'en_US'. ```python from faker import Factory fake = Factory.create('it_IT') for _ in range(0,10): print fake.name() ``` -------------------------------- ### Simplified Faker Generator Creation with Faker() Source: https://context7.com/xfxf/faker-python/llms.txt A convenience function that wraps Factory.create() for simpler instantiation. This is the recommended way to create a Faker instance for most use cases. It allows for simple instantiation or instantiation with a specific locale. ```python from faker import Faker # Simple instantiation fake = Faker() print(fake.name()) # 'Margaret Boehm' print(fake.email()) # 'lucy.cechtelar@gmail.com' # With locale fake = Faker('de_DE') print(fake.name()) # German name print(fake.address()) # German address format ``` -------------------------------- ### Initialize Faker Generator with Factory.create() Source: https://context7.com/xfxf/faker-python/llms.txt Creates and initializes a Faker generator instance with optional locale specification and custom providers. It automatically loads appropriate localized providers and falls back to en_US if the specified locale is unavailable. Custom providers can be included via a list of importable strings. ```python from faker import Factory # Create default generator (en_US locale) fake = Factory.create() print(fake.name()) # 'Lucy Cechtelar' print(fake.address()) # '426 Jordy Lodge\nCartwrightshire, SC 88120-6700' # Create localized generator for Italian fake_it = Factory.create('it_IT') print(fake_it.name()) # 'Elda Palumbo' print(fake_it.address()) # Italian address format # Create generator with custom providers from faker.providers import BaseProvider class MyProvider(BaseProvider): def custom_data(self): return 'custom_value' # Note: The actual inclusion of custom providers would depend on your project structure # fake = Factory.create(includes=['myapp.custom_provider']) # Example usage ``` -------------------------------- ### Seeding the Faker Generator Source: https://github.com/xfxf/faker-python/blob/master/README.rst This Python code demonstrates how to seed the Faker random number generator. By calling the seed() method with a specific integer, subsequent calls to generate fake data will produce the same results, which is useful for unit testing. ```python from faker import Faker fake = Faker() fake.seed(4321) print fake.name() > Margaret Boehm ``` -------------------------------- ### Generate URLs and URIs with Faker Source: https://context7.com/xfxf/faker-python/llms.txt Creates realistic URLs, URIs, and image placeholder URLs. Includes options for generating full URLs, URI paths, extensions, and specific image dimensions for placeholders. ```python from faker import Faker fake = Faker() # Random URL print(fake.url()) # 'http://www.acmecorp.com/' # URL with URI path print(fake.uri()) # 'http://www.example.com/search/category/posts.html' # URL components print(fake.uri_page()) # 'index' print(fake.uri_path()) # 'app/main/search' print(fake.uri_extension()) # '.html' # Image placeholder URLs print(fake.image_url()) # 'http://www.lorempixel.com/640/480' print(fake.image_url(width=1024, height=768)) # 'http://dummyimage.com/1024x768' ``` -------------------------------- ### Generate Multiple Fake Names (Python) Source: https://github.com/xfxf/faker-python/blob/master/docs/index.rst This Python snippet shows how to generate multiple fake names by iterating a set number of times. It utilizes the Faker library to produce different names on each iteration. ```python from faker import Faker fake = Faker() for _ in range(0,10): print(fake.name()) # Example Output: # 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 ``` -------------------------------- ### Generate Lorem Ipsum Text with fake.text() Source: https://context7.com/xfxf/faker-python/llms.txt Generates placeholder text with a specified maximum character length. It automatically adjusts the output format (words, sentences, or paragraphs) based on the requested length, making it ideal for populating text fields in testing scenarios. ```python from faker import Faker fake = Faker() # Generate text (default 200 chars) print(fake.text()) # 'Sint velit eveniet. Rerum atque repellat voluptatem quia rerum...' # Short text (words only) print(fake.text(max_nb_chars=20)) # 'Lorem ipsum dolor.' # Medium text (sentences) print(fake.text(max_nb_chars=80)) # Multiple sentences # Long text (paragraphs) print(fake.text(max_nb_chars=500)) # Multiple paragraphs ``` -------------------------------- ### Faker Integration: factory-boy for Model Data Generation Source: https://context7.com/xfxf/faker-python/llms.txt Demonstrates how to integrate Faker with the factory-boy library to generate realistic fake data for Django or SQLAlchemy models within model factories. Uses Faker's lazy attributes for dynamic data generation. ```python import factory from faker import Factory as FakerFactory from myapp.models import Book, User faker = FakerFactory.create() # Book factory class BookFactory(factory.Factory): class Meta: model = Book title = factory.LazyAttribute(lambda x: faker.sentence(nb_words=4)) author_name = factory.LazyAttribute(lambda x: faker.name()) isbn = factory.LazyAttribute(lambda x: faker.numerify(text='###-#-##-######-#')) published_date = factory.LazyAttribute(lambda x: faker.date()) description = factory.LazyAttribute(lambda x: faker.text(max_nb_chars=200)) ``` -------------------------------- ### Faker: Unit Testing with Deterministic Data (Faker.seed) Source: https://context7.com/xfxf/faker-python/llms.txt Shows how to use Faker.seed() in unit tests to ensure deterministic data generation. This allows for predictable test outcomes and reliable assertions by seeding the random number generator with a fixed value. ```python # Use in unit tests def test_user_creation(): fake = Faker() fake.seed(42) user = create_user( name=fake.name(), email=fake.email(), address=fake.address() ) assert user.name == 'Expected Name' # Deterministic ``` -------------------------------- ### Faker CLI: Generate Data from Terminal Source: https://context7.com/xfxf/faker-python/llms.txt Provides command-line interface for generating fake data without writing Python code. Supports localization, generating multiple entries, custom separators, specific fields, outputting to files, and using custom providers. ```bash # Basic usage faker name # Lucy Cechtelar faker address # 426 Jordy Lodge # Cartwrightshire, SC 88120-6700 # Localized output faker -l de_DE name # Hans Müller faker -l fr_FR address # 12 Rue de la Paix # 75001 Paris # Generate multiple entries faker -r 5 name # Generates 5 names # Custom separator faker -r 3 -s "," email # email1@example.com,email2@example.com,email3@example.com # Profile with specific fields faker profile ssn,birthdate # {'ssn': '628-10-1085', 'birthdate': '2008-03-29'} # Output to file faker -r 100 -o users.txt name # Custom providers faker -i myapp.providers -l en_US custom_method # Chain with shell commands for i in {1..10}; do echo "INSERT INTO users (name, email) VALUES ('$(faker name)', '$(faker email)');" done > seed_data.sql ``` -------------------------------- ### Faker: Pattern-Based String Generation (numerify, lexify, bothify) Source: https://context7.com/xfxf/faker-python/llms.txt Generates strings by replacing placeholders with digits or letters, useful for creating formatted codes, identifiers, and structured data like custom license plates or SKUs. ```python from faker import Faker fake = Faker() # numerify: Replace # with digits, % with non-zero digits print(fake.numerify(text='###-###-####')) # '555-123-4567' print(fake.numerify(text='Order #####')) # 'Order 12345' print(fake.numerify(text='%##')) # '512' (first digit non-zero) # lexify: Replace ? with letters print(fake.lexify(text='????')) # 'AbCd' print(fake.lexify(text='Product-????')) # 'Product-XyZw' # bothify: Replace both numbers and letters print(fake.bothify(text='??-##??')) # 'Ab-12Cd' print(fake.bothify(text='Serial: ????-####')) # 'Serial: XyZw-5678' # Custom license plates, SKUs, etc. license_plate = fake.bothify(text='??##-???') # 'AB12-XYZ' product_sku = fake.bothify(text='SKU-####-??') # 'SKU-1234-AB' ``` -------------------------------- ### Python: Create User Factory with Faker Source: https://context7.com/xfxf/faker-python/llms.txt Defines a UserFactory using factory-boy to generate mock User objects with realistic data like username, email, and birth date, leveraging Faker providers. This is useful for populating databases or creating test data. ```python from faker import Faker faker = Faker() class UserFactory(factory.Factory): class Meta: model = User username = factory.LazyAttribute(lambda x: faker.user_name()) email = factory.LazyAttribute(lambda x: faker.email()) first_name = factory.LazyAttribute(lambda x: faker.first_name()) last_name = factory.LazyAttribute(lambda x: faker.last_name()) birth_date = factory.LazyAttribute(lambda x: faker.date_time_between( start_date='-50y', end_date='-18y' )) ``` -------------------------------- ### Python: Test Book Creation Source: https://context7.com/xfxf/faker-python/llms.txt A test function demonstrating the creation of a Book object using a factory. It asserts that the generated book has a non-null title and a specific length for its ISBN, useful for verifying factory output. ```python # Assuming BookFactory is defined elsewhere # from .factories import BookFactory def test_create_book(): book = BookFactory() assert book.title is not None assert len(book.isbn) == 17 ``` -------------------------------- ### Generate User Profiles with Faker Source: https://context7.com/xfxf/faker-python/llms.txt Creates comprehensive user profiles with various personal and contact details. Supports generating full profiles, simple profiles with basic fields, or profiles with selectively chosen fields. ```python from faker import Faker fake = Faker() # Full profile profile = fake.profile() print(profile) # { # 'job': 'Software Engineer', # 'company': 'Acme Corp', # 'ssn': '628-10-1085', # 'residence': '426 Jordy Lodge\nCartwrightshire, SC 88120', # 'current_location': (Decimal('40.7128'), Decimal('-74.0060')), # 'blood_group': 'A+', # 'website': ['http://www.example.com/', 'http://test.org/'], # 'username': 'lucy.cechtelar', # 'name': 'Lucy Cechtelar', # 'sex': 'F', # 'address': '426 Jordy Lodge\nCartwrightshire, SC 88120', # 'mail': 'lucy@gmail.com', # 'birthdate': '2008-03-29' # } # Simple profile (basic fields only) simple = fake.simple_profile() print(simple) # { # 'username': 'john.doe', # 'name': 'John Doe', # 'sex': 'M', # 'address': '123 Main St', # 'mail': 'john.doe@hotmail.com', # 'birthdate': '1985-06-15' # } # Selective fields profile = fake.profile(fields=['username', 'name', 'mail']) print(profile) # {'username': 'jane.smith', 'name': 'Jane Smith', 'mail': 'jane@yahoo.com'} ``` -------------------------------- ### Generate Email Addresses with fake.email() Source: https://context7.com/xfxf/faker-python/llms.txt Creates realistic email addresses using various domain patterns, including free email providers and company domains. Usernames are derived from person names with proper formatting. It supports generating random, free, safe, and company-specific emails. ```python from faker import Faker fake = Faker() # Random email (free or company domain) print(fake.email()) # 'lucy.cechtelar@gmail.com' # Free email (gmail, yahoo, hotmail) print(fake.free_email()) # 'john.doe@yahoo.com' # Safe email (example.org/com/net) print(fake.safe_email()) # 'jane.smith@example.org' # Company email print(fake.company_email()) # 'bob.johnson@acmecorp.com' # Email components print(fake.user_name()) # 'lucy.cechtelar' print(fake.domain_name()) # 'acmecorp.com' print(fake.free_email_domain()) # 'gmail.com' ``` -------------------------------- ### Generate Person Names with fake.name() Source: https://context7.com/xfxf/faker-python/llms.txt Generates random full names using locale-specific name patterns and data. The format varies by locale and may include prefixes, suffixes, and culturally appropriate name structures. It also supports generating gender-specific names and individual name components. ```python from faker import Faker fake = Faker() # Generate multiple names for _ in range(5): print(fake.name()) # Output: # Adaline Reichel # Dr. Santa Prosacco DVM # Noemy Vandervort V # Lexi O'Conner # Gracie Weber # Gender-specific names print(fake.name_male()) # Male name print(fake.name_female()) # Female name # Name components print(fake.first_name()) # 'John' print(fake.last_name()) # 'Doe' print(fake.prefix()) # 'Dr.' print(fake.suffix()) # 'Jr.' ``` -------------------------------- ### Faker: Extending Functionality with Custom Providers (add_provider) Source: https://context7.com/xfxf/faker-python/llms.txt Allows extending Faker's capabilities by adding custom provider classes. This enables the generation of domain-specific or application-specific data, such as game character classes or weapon types. ```python from faker import Faker from faker.providers import BaseProvider # Define custom provider class GameProvider(BaseProvider): def character_class(self): classes = ['Warrior', 'Mage', 'Rogue', 'Cleric'] return self.random_element(classes) def weapon(self): weapons = ['Sword', 'Staff', 'Dagger', 'Mace'] return self.random_element(weapons) def skill_level(self): return self.random_int(min=1, max=100) # Add provider to Faker instance fake = Faker() fake.add_provider(GameProvider) # Use custom methods print(fake.character_class()) # 'Warrior' print(fake.weapon()) # 'Sword' print(fake.skill_level()) # 87 # Create game character character = { 'name': fake.name(), 'class': fake.character_class(), 'weapon': fake.weapon(), 'level': fake.skill_level() } ``` -------------------------------- ### Generate Addresses with fake.address() Source: https://context7.com/xfxf/faker-python/llms.txt Generates complete postal addresses formatted according to the selected locale's conventions, including street, city, state/province, and postal code. This is useful for data seeding and testing applications that handle addresses. ```python from faker import Faker fake = Faker() # Full address print(fake.address()) # '426 Jordy Lodge\nCartwrightshire, SC 88120-6700' # UK addresses fake_uk = Faker('en_GB') print(fake_uk.address()) # British address format with postcode # Multiple addresses for data seeding addresses = [fake.address() for _ in range(10)] ``` -------------------------------- ### Generate IP Addresses with Faker Source: https://context7.com/xfxf/faker-python/llms.txt Generates random IPv4, IPv6, and MAC addresses. Useful for network testing, simulating network traffic, or populating network-related fields in databases. ```python from faker import Faker fake = Faker() # IPv4 address print(fake.ipv4()) # '192.168.1.42' # IPv6 address print(fake.ipv6()) # '2001:0db8:85a3:0000:0000:8a2e:0370:7334' # MAC address print(fake.mac_address()) # '00:0a:95:9d:68:16' # Generate multiple for network simulation ip_addresses = [fake.ipv4() for _ in range(10)] ``` -------------------------------- ### Generate Date Strings with Faker Source: https://context7.com/xfxf/faker-python/llms.txt Generates formatted date strings using Python's strftime format codes. Supports default YYYY-MM-DD format and custom patterns, as well as individual date components like year, month, day, and day of the week. ```python from faker import Faker fake = Faker() # Default format (YYYY-MM-DD) print(fake.date()) # '2008-11-27' # Custom formats print(fake.date(pattern='%d/%m/%Y')) # '27/11/2008' print(fake.date(pattern='%B %d, %Y')) # 'November 27, 2008' # Date components print(fake.year()) # '2008' print(fake.month()) # '11' print(fake.month_name()) # 'November' print(fake.day_of_month()) # '27' print(fake.day_of_week()) # 'Thursday' ``` -------------------------------- ### Faker: Random Element Selection and Utilities (random_element, random_digit) Source: https://context7.com/xfxf/faker-python/llms.txt Selects random elements from collections like lists or dictionaries, with support for weighted probabilities. Includes utilities for generating random digits, non-zero digits, integers within a range, and letters. ```python from faker import Faker fake = Faker() # Random element from list colors = ['red', 'blue', 'green', 'yellow'] print(fake.random_element(elements=colors)) # 'blue' # Weighted selection from dictionary choices = { 'common': 0.7, # 70% probability 'uncommon': 0.2, # 20% probability 'rare': 0.08, # 8% probability 'legendary': 0.02 # 2% probability } print(fake.random_element(elements=choices)) # 'common' (most likely) # Random digit utilities print(fake.random_digit()) # 0-9 print(fake.random_digit_not_null()) # 1-9 print(fake.random_int(min=1, max=100)) # 1-100 print(fake.random_letter()) # 'A'-'Z' or 'a'-'z' ``` -------------------------------- ### Generate Fake Text with Faker Source: https://context7.com/xfxf/faker-python/llms.txt Generates various forms of fake text, including single words, lists of words, sentences, and paragraphs. Useful for populating text fields in applications or for placeholder content. ```python from faker import Faker fake = Faker() print(fake.word()) # 'Lorem' print(fake.words(nb=5)) # ['Lorem', 'ipsum', 'dolor', 'sit', 'amet'] print(fake.sentence()) # 'Lorem ipsum dolor sit amet.' print(fake.paragraph()) # Full paragraph ``` -------------------------------- ### Generate DateTime Objects with Faker Source: https://context7.com/xfxf/faker-python/llms.txt Creates random Python datetime objects within specified ranges or relative to the current time. Supports generating datetimes between specific dates, this year, month, decade, and Unix timestamps or ISO format strings. ```python from faker import Faker from datetime import datetime fake = Faker() # Random datetime (1970 to now) dt = fake.date_time() print(dt) # datetime(2005, 8, 16, 20, 39, 21) # DateTime between specific dates dt = fake.date_time_between(start_date='-30y', end_date='now') print(dt) # datetime from last 30 years dt = fake.date_time_between(start_date='-1y', end_date='+1y') print(dt) # datetime within ±1 year # DateTime from specific datetime objects start = datetime(2020, 1, 1) end = datetime(2023, 12, 31) dt = fake.date_time_between_dates(datetime_start=start, datetime_end=end) # Relative datetime dt = fake.date_time_this_year() # This year dt = fake.date_time_this_month() # This month dt = fake.date_time_this_decade() # This decade # Unix timestamp timestamp = fake.unix_time() # 1061306726 # ISO format iso_str = fake.iso8601() # '2003-10-21T16:05:52' ``` -------------------------------- ### Seed Faker's Random Generator Source: https://context7.com/xfxf/faker-python/llms.txt Seeds the random number generator to ensure reproducible fake data generation. This is crucial for unit testing and scenarios where consistent test data is required across multiple runs. ```python from faker import Faker # Create two generators with same seed fake1 = Faker() fake1.seed(4321) print(fake1.name()) # 'Margaret Boehm' fake2 = Faker() fake2.seed(4321) print(fake2.name()) # 'Margaret Boehm' (same output) # Different seed produces different data fake3 = Faker() fake3.seed(1234) print(fake3.name()) # Different name ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.