### Install russian-names with pip Source: https://github.com/cybermatt/russian-names/blob/master/README.rst Install the library using pip. This is the standard method for adding Python packages to your project. ```bash $ pip install russian-names ``` -------------------------------- ### Internal Data Structure Example Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Provides an example of the expected format for the internal data list used by RussianNames.read_data(). Each string contains space-separated names, patronymics, or surnames categorized by rarity and gender. ```python data = [ 'Архип Терентий', # Rare male names 'Иван Петр Сергей', # Common male names 'Архипович Терентьевич', # Rare male patronymics 'Иванович Петрович Сергеевич', # Common male patronymics 'Иванов Петров Сергеев', # Male surnames 'Архипа Терентия', # Rare female names 'Иванна Петра Сергея', # Common female names 'Архипова Терентьева', # Rare female patronymics 'Ивановна Петровна Сергеевна', # Common female patronymics 'Иванова Петрова Сергеева', # Female surnames ] ``` -------------------------------- ### Import RussianNames class Source: https://github.com/cybermatt/russian-names/blob/master/README.rst Import the necessary class from the library to start generating names. ```python >>> from russian_names import RussianNames ``` -------------------------------- ### Python Mock Data Generation for Database Seeding Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Generate mock user data for database seeding. This example configures the generator for a large count, balanced gender, transliteration, and dictionary output, then iterates to insert data. ```python from russian_names import RussianNames # Create mock users for database seeding rn = RussianNames( count=1000, gender=0.5, transliterate=True, output_type='dict' ) for person in rn.get_batch(): # Insert into database db.users.insert_one({ 'full_name': f"{person['name']} {person['surname']}", 'patronymic': person['patronymic'], }) ``` -------------------------------- ### Get Name in Dictionary Format Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a full name and returns it as a dictionary with keys for 'name', 'patronymic', and 'surname'. ```python RussianNames(output_type='dict').get_person() ``` -------------------------------- ### Get Uppercase Name Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a full name in all uppercase letters. ```python RussianNames(uppercase=True).get_person() ``` -------------------------------- ### Example PATRONYMIC_RULES Structure Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Illustrates the structure of the PATRONYMIC_RULES dictionary, showing keys as tuples of last characters and values as tuples containing a boolean flag and male/female suffixes. ```python PATRONYMIC_RULES = { ('н', 'с', 'т', 'р', ...): (False, 'ович', 'овна'), ('а',): (True, 'ич', 'ична'), ('й', 'ь'): (True, 'евич', 'евна'), } ``` -------------------------------- ### Generate Multiple Names with Options Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Initialize RussianNames with specific options like count, patronymic inclusion, and transliteration. Iterate over the generator to get multiple names. ```python rn = RussianNames(count=5, patronymic=False, transliterate=True) for name in rn: print(name) ``` -------------------------------- ### Get a Batch of Names Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a specified number of full names. The default count is 5. ```python RussianNames(count=5).get_batch() ``` -------------------------------- ### Python Localized Credit Card Names (Cyrillic and Latin) Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Generate localized names for credit card fields. This example shows how to create batches of names in both Cyrillic and transliterated Latin scripts. ```python from russian_names import RussianNames # Cyrillic names rn_cyrillic = RussianNames(count=10, patronymic=False) cyrillic_batch = rn_cyrillic.get_batch() # Latin names rn_latin = RussianNames(count=10, patronymic=False, transliterate=True) latin_batch = rn_latin.get_batch() ``` -------------------------------- ### Get Batch of Names (Dictionary Output) Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Retrieves a batch of names formatted as a tuple of dictionaries. Initialize the RussianNames object with output_type='dict'. Each dictionary contains 'name', 'patronymic', and 'surname'. ```python # Dictionary output rn = RussianNames(count=3, output_type='dict') batch = rn.get_batch() # Result: # ( # {'name': 'Кирилл', 'patronymic': 'Денисович', 'surname': 'Дрожжов'}, # {'name': 'Андрей', 'patronymic': 'Кириллович', 'surname': 'Шувиков'}, # {'name': 'Роман', 'patronymic': 'Евгеньевич', 'surname': 'Малеванкин'} # ) ``` -------------------------------- ### Get Batch of Names (String Output) Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Retrieves a batch of names formatted as a tuple of strings. Ensure the RussianNames object is initialized with output_type='str'. ```python # String output rn = RussianNames(count=3, output_type='str') batch = rn.get_batch() # Result: ('Иван Иванович Иванов', 'Петр Петрович Петров', 'Сергей Сергеевич Соколов') ``` -------------------------------- ### Get a Single Person's Name Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a single full name (first, patronymic, surname). ```python RussianNames().get_person() ``` -------------------------------- ### Get Female Name Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a full name, specifically a female one, by setting the gender probability to 0.0. ```python RussianNames(gender=0.0).get_person() ``` -------------------------------- ### Generate a Single Person Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Use this pattern to generate a single full name including first name, patronymic, and surname. No special setup is required beyond initializing the RussianNames class. ```python from russian_names import RussianNames rn = RussianNames() person = rn.get_person() print(person) # 'Владислав Николаевич Ильин' ``` -------------------------------- ### Print Current RussianNames Options Source: https://github.com/cybermatt/russian-names/blob/master/README.rst Instantiates RussianNames with various settings and prints the current configuration. ```python >>> rn = RussianNames(count=10, gender=0.5, surname_max_len=15, transliterate=True, uppercase=True) >>> print(rn) RussianNames settings: name: True name_reduction: False name_max_len: 10 patronymic: True patronymic_reduction: False patronymic_max_len: 10 surname: True surname_reduction: False surname_max_len: 15 count: 10 gender: 0.5 transliterate: True output_type: str seed: None rare: False uppercase: True ``` -------------------------------- ### Get Transliterated Name Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a full name with Latin transliteration. ```python RussianNames(transliterate=True).get_person() ``` -------------------------------- ### Import Utility Functions from russian_names.utils Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Import utility functions for transliteration, surname suffix checking, file I/O, and patronymic generation. ```python from russian_names.utils import ( transliterate_word, # str → str (Cyrillic to Latin) check_suffix, # Check surname suffix read_file, # File I/O save_file, # File I/O patronymic_from_name, # Generate patronymic create_patronymics, # Batch patronymic generation ) ``` -------------------------------- ### Generate Russian Names with RussianNames Class Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Demonstrates creating a RussianNames generator with specific parameters for count, gender, transliteration, and output type. Shows how to generate a single person and a batch of people, as well as iterating through the generator. ```python from russian_names import RussianNames # Create a generator rn = RussianNames( count=10, # Generate 10 persons per batch gender=0.5, # 50% male, 50% female transliterate=True, # Cyrillic to Latin output_type='str' # Space-separated string ) # Generate single person person = rn.get_person() # 'Vladislav Nikolaevich Ilin' # Generate batch batch = rn.get_batch() # ('Vladislav Nikolaevich Ilin', 'Ivan Ivanovich Ivanov', ...) # Iterate for person in RussianNames(count=5): print(person) ``` -------------------------------- ### Get Name Only Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates only the first name by disabling the inclusion of patronymic and surname. ```python RussianNames(patronymic=False, surname=False).get_person() ``` -------------------------------- ### Get Abbreviated Name Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates an abbreviated full name where the first name is reduced. ```python RussianNames(name_reduction=True).get_person() ``` -------------------------------- ### Load Name Data from ZIP Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Loads name data from a compressed ZIP file. Ensure the ZIP file and its contents are correctly placed relative to the module. ```python def load_data(): path = abspath(join(dirname(__file__), _BASE_PATH)) data_zip = zipfile.ZipFile(path) data = data_zip.read(_BASE_NAME) data_decoded = data.decode('utf8') return data_decoded.splitlines() ``` -------------------------------- ### Get Reproducible Name Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a full name that is reproducible by providing a specific seed value. ```python RussianNames(seed=42).get_person() ``` -------------------------------- ### Get Short Name Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Generates a full name ensuring that only names with a maximum length of 4 characters are selected. ```python RussianNames(name_max_len=4).get_person() ``` -------------------------------- ### Name Data Structure Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Illustrates the expected structure of the loaded name data, organized by categories like male/female names, patronymics, and surnames. ```python [ 'Архип Терентий ...', # data[0]: Rare male names 'Иван Петр Сергей ...', # data[1]: Common male names 'Архипович Терентьевич ...', # data[2]: Rare male patronymics 'Иванович Петрович ...', # data[3]: Common male patronymics 'Иванов Петров Сергеев ...', # data[4]: Male surnames 'Архипа Терентия ...', # data[5]: Rare female names 'Иванна Петра Сергея ...', # data[6]: Common female names 'Архипова Терентьева ...', # data[7]: Rare female patronymics 'Ивановна Петровна ...', # data[8]: Common female patronymics 'Иванова Петрова Сергеева ...',# data[9]: Female surnames ] ``` -------------------------------- ### Display Configuration - RussianNames __str__ Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Returns a formatted string representation of all current configuration settings for the RussianNames instance. Useful for debugging or verifying settings. ```python from russian_names import RussianNames rn = RussianNames(count=10, gender=0.5, surname_max_len=15, transliterate=True, uppercase=True) print(rn) # RussianNames settings: # name: True # name_reduction: False # name_max_len: 10 # patronymic: True # patronymic_reduction: False # patronymic_max_len: 10 # surname: True # surname_reduction: False # surname_max_len: 15 # count: 10 # gender: 0.5 # transliterate: True # output_type: str # seed: None # rare: False # uppercase: True ``` -------------------------------- ### Initialize RussianNames Generator Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Instantiate the RussianNames class to create a name generator. Configuration options can be passed during initialization to customize name generation. ```python rn = RussianNames() ``` -------------------------------- ### Get Number of Persons to Generate (__len__) Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Returns the count parameter, indicating the number of persons to generate. Used with the len() function. ```python def __len__(self): return self.count ``` -------------------------------- ### Python Test Fixture for User Registration Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Use this snippet to create test fixtures for user registration scenarios. It generates a batch of names and asserts the expected count. ```python from russian_names import RussianNames def test_user_registration(): rn = RussianNames(count=100, seed=12345) users = [(n, i+1) for i, n in enumerate(rn.get_batch())] assert len(users) == 100 ``` -------------------------------- ### Generate Transliterated Female Names Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Configure the generator for a specific gender (0.0 for all female) and enable transliteration to get Latin alphabet names. ```python rn = RussianNames(gender=0.0, transliterate=True) print(rn.get_person()) ``` -------------------------------- ### RussianNames Constructor Configuration Dictionary Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Defines the structure of the configuration dictionary used for initializing the RussianNames class. Each key represents a configurable parameter with its expected data type. ```python { 'name': bool, 'name_reduction': bool, 'name_max_len': int, 'patronymic': bool, 'patronymic_reduction': bool, 'patronymic_max_len': int, 'surname': bool, 'surname_reduction': bool, 'surname_max_len': int, 'count': int, 'gender': float, 'transliterate': bool, 'output_type': str, 'seed': int | None, 'rare': bool, 'uppercase': bool, } ``` -------------------------------- ### __str__ Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Provides a formatted string representation of all current configuration settings for the RussianNames object. ```APIDOC ## Method: __str__ ### Description Returns a formatted string representation of all configuration settings for the `RussianNames` object. ### Return Type String with all constructor options and their current values. ### Example ```python from russian_names import RussianNames rn = RussianNames(count=10, gender=0.5, surname_max_len=15, transliterate=True, uppercase=True) print(rn) # RussianNames settings: # name: True # name_reduction: False # name_max_len: 10 # patronymic: True # patronymic_reduction: False # patronymic_max_len: 10 # surname: True # surname_reduction: False # surname_max_len: 15 # count: 10 # gender: 0.5 # transliterate: True # output_type: str # seed: None # rare: False # uppercase: True ``` ``` -------------------------------- ### Initialize Russian Names Generator (__init__) Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Initializes the generator with optional keyword arguments for properties and a seed for random number generation. Populates internal data after setting options. ```python def __init__(self, **kwargs): prop_defaults = { ... } seed = kwargs.pop('seed', None) if seed is not None: random.seed(seed) for prop, default in prop_defaults.items(): setattr(self, prop, kwargs.get(prop, default)) self._fill_base() ``` -------------------------------- ### List Output Type Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Use 'list' for an ordered list of name components. The order is name, patronymic, surname. Values can be strings or None. ```python output_type = 'list' ``` ```python rn = RussianNames(output_type='list') person = rn.get_person() # Result: ['Кирилл', 'Денисович', 'Дрожжов'] # Access by index: name, patronymic, surname = person ``` -------------------------------- ### Get Name Count - RussianNames __len__ Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Returns the configured number of names to generate. Use when you need to know the total count of names the instance is set to produce. ```python from russian_names import RussianNames rn = RussianNames(count=15) print(len(rn)) # 15 ``` -------------------------------- ### Constructor Option Validation (No Errors) Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/configuration.md Demonstrates that the RussianNames constructor does not raise errors for invalid option values during initialization. Issues may arise later during data generation. ```python # These don't raise errors during initialization rn = RussianNames( count=-5, # Will cause issues in iteration name_max_len=0, # No names match this filter gender=1.5, # Out of range, defaults to 0.5 ) ``` -------------------------------- ### Initialize Random Seed for Reproducible Generation Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/configuration.md Use the `seed` parameter to initialize Python's `random` module for reproducible results. Setting the same seed will produce the same batch of names. ```python rn1 = RussianNames(seed=42, count=5) batch1 = rn1.get_batch() rn2 = RussianNames(seed=42, count=5) batch2 = rn2.get_batch() assert batch1 == batch2 # Same results ``` -------------------------------- ### Run Pytest Tests Source: https://github.com/cybermatt/russian-names/blob/master/README.rst Executes the project's tests using pytest with verbose output. ```bash $ pytest -v tests/* ``` -------------------------------- ### RussianNames Constructor Options Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/configuration.md This snippet shows all available keyword arguments for the RussianNames constructor. Use these to customize name generation. ```python RussianNames( name=True, name_reduction=False, name_max_len=10, patronymic=True, patronymic_reduction=False, patronymic_max_len=10, surname=True, surname_reduction=False, surname_max_len=10, count=10, gender=0.5, transliterate=False, output_type='str', seed=None, rare=False, uppercase=False, ) ``` -------------------------------- ### String Output Type Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Use 'str' for space-separated name components. The order is name, patronymic, surname, skipping None values. ```python output_type = 'str' ``` ```python rn = RussianNames(output_type='str') person = rn.get_person() # Result: 'Владислав Николаевич Ильин' ``` -------------------------------- ### Data Format Description Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Describes the structure of the base.txt file within the _data.zip archive, detailing the content of each of the 10 lines. ```text [line 1] Rare male names (space-separated) [line 2] Common male names (space-separated) [line 3] Rare male patronymics (space-separated) [line 4] Common male patronymics (space-separated) [line 5] Male surnames (space-separated) [line 6] Rare female names (space-separated) [line 7] Common female names (space-separated) [line 8] Rare female patronymics (space-separated) [line 9] Common female patronymics (space-separated) [line 10] Female surnames (space-separated) ``` -------------------------------- ### save_file() Function Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Writes a list of words to a specified file, with options for encoding and sorting. ```APIDOC ## Function: save_file(path, words, encoding='cp1251', sorting=False) -> None ### Description Saves a list of words to a file, one word per line. Allows for custom encoding and optional sorting. ### Parameters - **path** (str) - Required - The path to the output file. - **words** (list) - Required - A list of words to write to the file. - **encoding** (str, optional) - The file encoding. Defaults to 'cp1251'. - **sorting** (bool, optional) - Whether to sort the words before writing. Defaults to False. ### Usage ```python from russian_names.utils import save_file my_names = ["test1", "test2"] save_file("output_names.txt", my_names, sorting=True) ``` ``` -------------------------------- ### Generate a batch of names Source: https://github.com/cybermatt/russian-names/blob/master/README.rst Create a batch of names using the get_batch method. The count option specifies the number of names to generate. name_reduction and patronymic options can be configured. ```python >>> rn = RussianNames(count=5, patronymic=False, name_reduction=True) >>> batch = rn.get_batch() >>> print(batch) ``` -------------------------------- ### Import Core Symbols from Russian Names Package Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Import the main generator class and utility functions from the package root. This is the primary way to access the library's core functionality. ```python from russian_names import ( RussianNames, load_data, __version__, __author__, ) ``` -------------------------------- ### RussianNames Constructor Options Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Details the various keyword arguments available for the RussianNames constructor, covering component selection, abbreviation, filtering, gender distribution, output format, transformations, and reproducibility. ```python RussianNames( # Component selection name=True, patronymic=True, surname=True, # Abbreviation name_reduction=False, patronymic_reduction=False, surname_reduction=False, # Filtering name_max_len=10, patronymic_max_len=10, surname_max_len=10, rare=False, # Gender distribution gender=0.5, # 0.0 = all female, 1.0 = all male # Output format output_type='str', # 'str', 'list', 'tuple', or 'dict' count=10, # Number of persons # Transformation transliterate=False, # Cyrillic to Latin uppercase=False, # Convert to uppercase # Reproducibility seed=None, # Random seed (None = non-deterministic) ) ``` -------------------------------- ### Import Core Components from RussianNames Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Import the main RussianNames class and utility functions for loading data and accessing version information. ```python from russian_names import ( RussianNames, # Main class load_data, # Load bundled data __version__, # '0.1.2' __author__, # 'Matt Stroganov' ) ``` -------------------------------- ### Handle Utility Function Returns Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/errors.md Check the return value of utility functions like `patronymic_from_name` as they may return None or an empty list for unsuccessful operations. Process only successful conversions. ```python from russian_names.utils import patronymic_from_name, create_patronymics # Single patronymic name = 'Иван' patronymic = patronymic_from_name(name, 'male') if patronymic: print(f"{name} → {patronymic}") # Batch conversion names = ['Иван', 'Петр', 'Unknown'] patronymics = create_patronymics(names) # Only successful conversions included ``` -------------------------------- ### Import Utilities from Russian Names Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Explicitly import utility functions for transliteration, suffix checking, file I/O, and patronymic generation. These are located in the `utils` submodule. ```python from russian_names.utils import ( transliterate_word, check_suffix, read_file, save_file, patronymic_from_name, create_patronymics, ) ``` -------------------------------- ### Utility Functions for Name Manipulation Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Illustrates the use of utility functions for transliterating Cyrillic words to Latin, generating a patronymic from a given name and gender, and creating patronymics for a batch of names. ```python from russian_names.utils import ( transliterate_word, patronymic_from_name, create_patronymics, ) # Convert Cyrillic to Latin print(transliterate_word('Владислав')) # 'Vladislav' # Generate patronymic print(patronymic_from_name('Иван', 'male')) # 'Иванович' # Batch generation names = {'Федор', 'Алексей'} patronymics = create_patronymics(names) # {'Федорович', 'Алексеевич'} ``` -------------------------------- ### Generate Multiple Names with get_batch Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Use the get_batch method to generate a specified number of names. Temporary option overrides can be passed as keyword arguments. This is useful for generating batches of names with specific configurations. ```python from russian_names import RussianNames # Generate 5 transliterated female names without patronymics rn = RussianNames(count=5, gender=0.0, patronymic=False, transliterate=True) batch = rn.get_batch() print(batch) # ('Irina Sidorova', 'Natalia Volkova', 'Ekaterina Fedorova', ...) ``` ```python from russian_names import RussianNames # Generate 3 male names with reductions for surname, as dictionaries rn = RussianNames(count=3, gender=1.0, output_type='dict', surname_reduction=True) batch = rn.get_batch() for person in batch: print(person) # {'name': 'Sergei', 'patronymic': 'Ivanovich', 'surname': 'S.'} # {'name': 'Alexei', 'patronymic': 'Petrovich', 'surname': 'P.'} # ... ``` -------------------------------- ### Safe File Reading with Error Handling Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/errors.md Implement try-except blocks to handle `FileNotFoundError` and `UnicodeDecodeError` when reading files. Attempt to read with UTF-8 encoding if the default encoding fails. ```python from russian_names.utils import read_file, save_file def safe_read_file(path, encoding='cp1251'): try: return read_file(path, encoding=encoding) except FileNotFoundError: print(f"File not found: {path}") return [] except UnicodeDecodeError: print(f"Encoding error: {path}. Trying UTF-8...") return read_file(path, encoding='utf-8') names = safe_read_file('./names.txt') ``` -------------------------------- ### load_data() Function Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Utility function to load the name database from a bundled ZIP archive. This is essential for the generator to function. ```APIDOC ## Function: load_data() ### Description Loads the name database from the bundled ZIP archive. This function should typically be called once before generating names. ### Purpose Initializes the name data required by the `RussianNames` class. ### Usage ```python from russian_names import load_data load_data() # Now you can use RussianNames ``` ``` -------------------------------- ### Handle patronymic_from_name failures Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/errors.md Demonstrates two methods for handling potential None return values from patronymic_from_name: explicit checking or filtering during batch creation. ```python from russian_names.utils import patronymic_from_name, create_patronymics # Method 1: Check for None patronymic = patronymic_from_name('Unknown', 'male') if patronymic is not None: print(f"Patronymic: {patronymic}") # Method 2: Filter out failures names = {'Иван', 'Федор', 'Странное'} patronymics = create_patronymics(names) # patronymics contains only successful conversions ``` -------------------------------- ### Constructor Option Validation (Errors on Generation) Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/configuration.md Shows that errors for invalid options, such as 'output_type', occur when generating data, not during object initialization. ```python rn = RussianNames(output_type='invalid') person = rn.get_person() # ValueError raised here ``` -------------------------------- ### Generate Structured Data with RussianNames Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Configure the library to output names as dictionaries, providing structured data for each generated name. ```python rn = RussianNames(count=5, output_type='dict') batch = rn.get_batch() # [ # {'name': 'Кирилл', 'patronymic': 'Денисович', 'surname': 'Дрожжов'}, # {'name': 'Андрей', 'patronymic': 'Кириллович', 'surname': 'Шувиков'}, # ... # ] ``` -------------------------------- ### Generate Batch of Persons Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Generates a batch of person data by repeatedly calling get_person. Note that using tuple concatenation (+=) in a loop can be inefficient for large batches; consider using a list and converting at the end. ```python def get_batch(self, **kwargs): batch = () for _ in range(self.count): fio = self.get_person(**kwargs) batch += (fio, ) return batch ``` -------------------------------- ### Utility Function - create_patronymics Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Creates patronymics for a collection of first names. ```APIDOC ## Batch Patronymic Generation ### Description Generates patronymics for a set of first names. ### Method `create_patronymics(names: set) -> set` ### Parameters - **names** (set) - A set of first names. ### Request Example ```python from russian_names.utils import create_patronymics first_names = {'Федор', 'Алексей'} patronymics = create_patronymics(first_names) print(patronymics) # Output: {'Федорович', 'Алексеевич'} ``` ### Response #### Success Response - **patronymics** (set) - A set of generated patronymic names. ``` -------------------------------- ### Input Data Pool Format Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Represents the raw input format for name data, which is a single space-separated string containing multiple names. ```text "Иван Петр Сергей" ``` -------------------------------- ### Import Constants from russian_names.consts Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/README.md Import constants related to transliteration, surname suffixes, and patronymic rules. ```python from russian_names.consts import ( TRANSLITERATE_TABLE, # dict SUFFIXES, # set SUFFIXES_MAN, # set SUFFIXES_WOMAN, # set PATRONYMIC_RULES, # dict ) ``` -------------------------------- ### RussianNames Constructor Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/RussianNames.md Initializes the RussianNames generator with a variety of configuration options to customize name generation. ```APIDOC ## RussianNames Constructor ### Description Initializes a RussianNames generator with configuration options. ### Method ```python RussianNames(**kwargs) -> RussianNames ``` ### Parameters #### Constructor Parameters - **name** (bool) - Optional - Default: True - Include given name in output - **name_reduction** (bool) - Optional - Default: False - Reduce name to first letter with period (e.g., 'Anna' → 'A.') - **name_max_len** (int) - Optional - Default: 10 - Maximum character length for names to include in selection pool - **patronymic** (bool) - Optional - Default: True - Include patronymic (father's name derivative) in output - **patronymic_reduction** (bool) - Optional - Default: False - Reduce patronymic to first letter with period (e.g., 'Fedorovich' → 'F.') - **patronymic_max_len** (int) - Optional - Default: 10 - Maximum character length for patronymics to include in selection pool - **surname** (bool) - Optional - Default: True - Include surname in output - **surname_reduction** (bool) - Optional - Default: False - Reduce surname to first letter with period (e.g., 'Ivanov' → 'I.') - **surname_max_len** (int) - Optional - Default: 10 - Maximum character length for surnames to include in selection pool - **count** (int) - Optional - Default: 10 - Number of persons to generate in batch operations - **gender** (float) - Optional - Default: 0.5 - Gender distribution: 0.0 = all female, 1.0 = all male, 0.5 = mixed - **transliterate** (bool) - Optional - Default: False - Convert cyrillic to latin alphabet (e.g., 'Владислав' → 'Vladislav') - **output_type** (str) - Optional - Default: 'str' - Output format: 'str' (space-separated), 'list', 'tuple', or 'dict' - **seed** (int) - Optional - Default: None - Random seed for reproducible results. If set, determines all random generation - **rare** (bool) - Optional - Default: False - Include rare/uncommon names in selection pool - **uppercase** (bool) - Optional - Default: False - Convert all output to uppercase ### Return Type RussianNames instance configured with the given options. ### Raises No exceptions raised by constructor. ### Example ```python from russian_names import RussianNames # Basic usage rn = RussianNames() person = rn.get_person() print(person) # 'Владислав Николаевич Ильин' # With options rn = RussianNames(count=5, patronymic=False, transliterate=True) for name in rn: print(name) # 'Valeriy Forunin', 'Pavel Senakosov', ... # Women only, transliterated rn = RussianNames(gender=0.0, transliterate=True) print(rn.get_person()) # 'Irina Petrovna Sidorova' ``` ``` -------------------------------- ### Save List of Words to File Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/utils.md Writes a list of strings to a specified file, with options for encoding and sorting. Parent directories are created if they don't exist, and existing files are overwritten. ```python from russian_names.utils import save_file names = ['Иван', 'Петр', 'Сергей'] # Write as-is save_file('./output_names.txt', names) # Write sorted save_file('./output_names_sorted.txt', names, sorting=True) # Write with UTF-8 encoding save_file('./output_utf8.txt', names, encoding='utf-8') ``` -------------------------------- ### Generate Structured Data in Dictionary Format Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/configuration.md Configure the generator to output names in a structured dictionary format by setting `output_type='dict'`. Each entry will contain 'name', 'patronymic', and 'surname' keys. ```python rn = RussianNames( count=10, output_type='dict', ) batch = rn.get_batch() # [ # {'name': 'Кирилл', 'patronymic': 'Денисович', 'surname': 'Дрожжов'}, # ... # ] ``` -------------------------------- ### Initialize RussianNames for All Female Names Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Initializes the RussianNames generator to produce only female names by setting the gender parameter to 0.0. ```python # All female rn = RussianNames(gender=0.0) ``` -------------------------------- ### load_data Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/utils.md Loads the Russian names dataset from the bundled archive. ```APIDOC ## Function: load_data ### Description Loads the Russian names dataset from the bundled `_data.zip` archive. This function is called automatically during package initialization. ### Parameters None ### Return Type List of 10 strings, each containing space-separated words for a category of names/patronymics/surnames. ### Example ```python from russian_names.utils import load_data data = load_data() print(len(data)) # 10 # Structure of returned data: # data[0]: Rare male names (space-separated) # data[1]: Common male names (space-separated) # data[2]: Rare male patronymics (space-separated) # data[3]: Common male patronymics (space-separated) # data[4]: Male surnames (space-separated) # data[5]: Rare female names (space-separated) # data[6]: Common female names (space-separated) # data[7]: Rare female patronymics (space-separated) # data[8]: Common female patronymics (space-separated) # data[9]: Female surnames (space-separated) ``` ``` -------------------------------- ### save_file Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/utils.md Writes a list of strings to a specified file, with options for encoding and sorting. ```APIDOC ## Function: save_file ### Description Writes a list of words/names to a file, one per line. Creates parent directories if they don't exist and overwrites existing files. ### Parameters #### Path Parameters - **path_out** (str) - Required - Output file path (created or overwritten) - **words** (list) - Required - List of strings to write - **encoding** (str) - Optional - File encoding, defaults to 'cp1251' - **sorting** (bool) - Optional - Whether to sort words alphabetically before writing, defaults to False ### Example ```python from russian_names.utils import save_file names = ['Иван', 'Петр', 'Сергей'] # Write as-is save_file('./output_names.txt', names) # Write sorted save_file('./output_names_sorted.txt', names, sorting=True) # Write with UTF-8 encoding save_file('./output_utf8.txt', names, encoding='utf-8') ``` ``` -------------------------------- ### Initialize RussianNames for All Male Names Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Initializes the RussianNames generator to produce only male names by setting the gender parameter to 1.0. ```python # All male rn = RussianNames(gender=1.0) ``` -------------------------------- ### Generate Credit Card Holder Names Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/configuration.md Configure the generator to produce names suitable for credit card holders, including transliteration and uppercase formatting. ```python rn = RussianNames( count=10, patronymic=False, transliterate=True, uppercase=True, ) batch = rn.get_batch() # ('SEMEN SISYKIN', 'LYBOV POLEZAEVA', 'MIHAIL KAMAGOROV', ...) ``` -------------------------------- ### Convert Output to Uppercase Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/configuration.md The `uppercase` option converts all generated output to uppercase. This can be used independently or in conjunction with other options like `transliterate`. ```python # Default (mixed case) rn = RussianNames(uppercase=False) # 'Владислав Николаевич Ильин' ``` ```python # Uppercase rn = RussianNames(uppercase=True) # 'ВЛАДИСЛАВ НИКОЛАЕВИЧ ИЛЬИН' ``` ```python # With transliteration rn = RussianNames(transliterate=True, uppercase=True) # 'VLADISLAV NIKOLAEVICH ILIN' ``` -------------------------------- ### Import Constants from Russian Names Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Import predefined constants for transliteration tables, surname suffixes, and patronymic generation rules. These are useful for custom logic or inspection. ```python from russian_names.consts import ( TRANSLITERATE_TABLE, SUFFIXES, SUFFIXES_MAN, SUFFIXES_WOMAN, PATRONYMIC_RULES, ) ``` -------------------------------- ### Generate a Person Object Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Generates a person object by selecting name, patronymic, and surname components. Allows temporary overrides for generation options. ```python def get_person(self, **kwargs): self._set_options(**kwargs) # Updates instance state temporarily gender = self._select_gender_distribution() name = self._get_object(gender, 'name', self.name_reduction) patronymic = self._get_object(gender, 'patronymic', self.patronymic_reduction) surname = self._get_object(gender, 'surname', self.surname_reduction) person = { 'name': name if self.name else None, 'patronymic': patronymic if self.patronymic else None, 'surname': surname if self.surname else None, } return self._format_person(person) ``` -------------------------------- ### Apply Temporary Option Overrides Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Applies temporary option overrides for name generation. Triggers data reconstruction if length-related options are changed. ```python def _set_options(self, **kwargs): refill_base = False for prop, value in kwargs.items(): if prop.endswith('_len'): refill_base = True setattr(self, prop, value) if refill_base: self._fill_base() # Expensive operation ``` -------------------------------- ### Load Russian Names Dataset Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/utils.md Loads the Russian names dataset from a bundled zip archive. This function is typically called automatically during package initialization. ```python from russian_names.utils import load_data data = load_data() print(len(data)) # 10 # Structure of returned data: # data[0]: Rare male names (space-separated) # data[1]: Common male names (space-separated) # data[2]: Rare male patronymics (space-separated) # data[3]: Common male patronymics (space-separated) # data[4]: Male surnames (space-separated) # data[5]: Rare female names (space-separated) # data[6]: Common female names (space-separated) # data[7]: Rare female patronymics (space-separated) # data[8]: Common female patronymics (space-separated) # data[9]: Female surnames (space-separated) ``` -------------------------------- ### Prevent File Leaks with Context Managers Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/implementation-details.md Ensure files are properly closed by using the 'with' statement for automatic resource management. This prevents file handle leaks. ```python f = open(path_in, 'r', encoding=encoding) words = f.read().splitlines()[:length] return words # File never explicitly closed ``` -------------------------------- ### Tuple Output Type Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/types.md Use 'tuple' for an immutable tuple of name components. The order is name, patronymic, surname. Values can be strings or None. ```python output_type = 'tuple' ``` ```python rn = RussianNames(output_type='tuple') person = rn.get_person() # Result: ('Андрей', 'Кириллович', 'Шувиков') # Unpack: name, patronymic, surname = person print(name) # 'Андрей' ``` -------------------------------- ### Reproducible Generation with Seed Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-overview.md Ensure reproducible results for testing or specific use cases by providing a 'seed' value during initialization. The same seed will always produce the same sequence of names. ```python from russian_names import RussianNames # Same seed = same results every run rn1 = RussianNames(count=10, seed=42) batch1 = rn1.get_batch() rn2 = RussianNames(count=10, seed=42) batch2 = rn2.get_batch() assert batch1 == batch2 ``` -------------------------------- ### read_file Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/api-reference/utils.md Reads a file containing one name/word per line and returns a list of strings. ```APIDOC ## Function: read_file ```python read_file(path_in: str, encoding: str = 'cp1251', length: int | None = None) -> list ``` ### Description Read a file containing one name/word per line and return a list of strings. ### Parameters #### Path Parameters - **path_in** (str) - Required - File path to read #### Query Parameters - **encoding** (str) - Optional - Default: 'cp1251' - File encoding (Windows Cyrillic by default) - **length** (int | None) - Optional - Default: None - Maximum number of lines to read (None = all lines) ### Return Type List of strings, one per line (without newlines). ### Example ```python from russian_names.utils import read_file # Read all names from a file names = read_file('./male_names.txt') print(len(names)) # Number of lines # Read only first 100 names rare_names = read_file('./rare_names.txt', length=100) # Read with UTF-8 encoding names = read_file('./names_utf8.txt', encoding='utf-8') ``` ### Notes - Default encoding is 'cp1251' (Windows Cyrillic), suitable for legacy Russian text files. - Trailing newlines are automatically removed by `splitlines()`. - Empty lines become empty strings in the result list. ``` -------------------------------- ### Catch ValueError for Invalid Output Type Source: https://github.com/cybermatt/russian-names/blob/master/_autodocs/errors.md Demonstrates how to catch a ValueError when an invalid output_type is specified during RussianNames initialization. This is useful for handling incorrect configurations gracefully. ```python from russian_names import RussianNames # Raises ValueError try: rn = RussianNames(output_type='json') # Invalid output type person = rn.get_person() except ValueError as e: print(f"Error: {e}") # Error: Output_type does not have value 'str', 'list, 'tuple' or 'dict'. ```