Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions faker/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ def print_doc(

while True:
try:
formatters = doc.get_formatters(with_args=True, with_defaults=True, excludes=unsupported)
formatters = doc.get_formatters(
with_args=True, with_defaults=True, excludes=unsupported
)
except exceptions.UnsupportedFeature as e:
unsupported.append(e.name)
else:
Expand Down Expand Up @@ -171,7 +173,9 @@ def execute(self) -> None:
formatter_class=formatter_class,
)

parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
parser.add_argument(
"--version", action="version", version=f"%(prog)s {VERSION}"
)

parser.add_argument(
"-v",
Expand Down
4 changes: 3 additions & 1 deletion faker/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"faker.providers",
]

PROVIDERS = find_available_providers([import_module(path) for path in META_PROVIDERS_MODULES])
PROVIDERS = find_available_providers(
[import_module(path) for path in META_PROVIDERS_MODULES]
)

AVAILABLE_LOCALES = find_available_locales(PROVIDERS)
4 changes: 3 additions & 1 deletion faker/documentor.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ def get_provider_formatters(
continue
formatters[signature] = example

self.max_name_len = max(self.max_name_len, *(len(part) for part in signature.split()))
self.max_name_len = max(
self.max_name_len, *(len(part) for part in signature.split())
)
self.already_generated.append(name)

return formatters
Expand Down
14 changes: 11 additions & 3 deletions faker/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def __init__(self, **config: Dict) -> None:
self.__config = dict(list(self.__config.items()) + list(config.items()))
self.__random = random

def add_provider(self, provider: Union["BaseProvider", Type["BaseProvider"]]) -> None:
def add_provider(
self, provider: Union["BaseProvider", Type["BaseProvider"]]
) -> None:
if isinstance(provider, type):
provider = provider(self)

Expand All @@ -48,7 +50,11 @@ def add_provider(self, provider: Union["BaseProvider", Type["BaseProvider"]]) ->

def provider(self, name: str) -> Optional["BaseProvider"]:
try:
lst = [p for p in self.get_providers() if hasattr(p, "__provider__") and p.__provider__ == name.lower()]
lst = [
p
for p in self.get_providers()
if hasattr(p, "__provider__") and p.__provider__ == name.lower()
]
return lst[0]
except IndexError:
return None
Expand Down Expand Up @@ -104,7 +110,9 @@ def set_formatter(self, name: str, formatter: Callable) -> None:
"""
setattr(self, name, formatter)

def set_arguments(self, group: str, argument: str, value: Optional[Any] = None) -> None:
def set_arguments(
self, group: str, argument: str, value: Optional[Any] = None
) -> None:
"""
Creates an argument group, with an individual argument or a dictionary
of arguments. The argument groups is used to apply arguments to tokens,
Expand Down
40 changes: 30 additions & 10 deletions faker/providers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,16 +380,22 @@ def random_number(self, digits: Optional[int] = None, fix_len: bool = False) ->
raise ValueError("The digit parameter must be greater than or equal to 0.")
if fix_len:
if digits > 0:
return self.generator.random.randint(pow(10, digits - 1), pow(10, digits) - 1)
return self.generator.random.randint(
pow(10, digits - 1), pow(10, digits) - 1
)
else:
raise ValueError("A number of fixed length cannot have less than 1 digit in it.")
raise ValueError(
"A number of fixed length cannot have less than 1 digit in it."
)
else:
return self.generator.random.randint(0, pow(10, digits) - 1)

def random_letter(self) -> str:
"""Generate a random ASCII letter (a-z and A-Z)."""

return self.generator.random.choice(getattr(string, "letters", string.ascii_letters))
return self.generator.random.choice(
getattr(string, "letters", string.ascii_letters)
)

def random_letters(self, length: int = 16) -> Sequence[str]:
"""Generate a list of random ASCII letters (a-z and A-Z) of the specified ``length``.
Expand Down Expand Up @@ -473,18 +479,24 @@ def random_elements(
("d", 0.05),
]), unique=True
"""
use_weighting = use_weighting if use_weighting is not None else self.__use_weighting__
use_weighting = (
use_weighting if use_weighting is not None else self.__use_weighting__
)

if isinstance(elements, dict) and not isinstance(elements, OrderedDict):
raise ValueError("Use OrderedDict only to avoid dependency on PYTHONHASHSEED (See #363).")
raise ValueError(
"Use OrderedDict only to avoid dependency on PYTHONHASHSEED (See #363)."
)

fn = choices_distribution_unique if unique else choices_distribution

if length is None:
length = self.generator.random.randint(1, len(elements))

if unique and length > len(elements):
raise ValueError("Sample length cannot be longer than the number of unique elements to pick from.")
raise ValueError(
"Sample length cannot be longer than the number of unique elements to pick from."
)

if isinstance(elements, dict):
if not hasattr(elements, "_key_cache"):
Expand Down Expand Up @@ -717,15 +729,19 @@ def __init__(
generator = Generator()
super().__init__(generator)
if provider_name.startswith("__"):
raise ValueError("Provider name cannot start with __ as it would be ignored by Faker")
raise ValueError(
"Provider name cannot start with __ as it would be ignored by Faker"
)

self.provider_name = provider_name

self.elements = []
if elements:
self.elements = elements

setattr(self, provider_name, self.get_random_value) # Add a method for the provider_name value
setattr(
self, provider_name, self.get_random_value
) # Add a method for the provider_name value

def add_element(self, element: str) -> None:
"""Add new element."""
Expand All @@ -737,6 +753,10 @@ def get_random_value(self, use_weighting: bool = True) -> Any:
:param use_weighting: boolean option to use weighting. Defaults to True
"""
if not self.elements or len(self.elements) == 0:
raise ValueError("Elements should be a list of values the provider samples from")
raise ValueError(
"Elements should be a list of values the provider samples from"
)

return self.random_elements(self.elements, length=1, use_weighting=use_weighting)[0]
return self.random_elements(
self.elements, length=1, use_weighting=use_weighting
)[0]
24 changes: 18 additions & 6 deletions faker/providers/address/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,19 @@ class Provider(BaseProvider):
address_formats: ElementsType[str] = ("{{street_address}} {{postcode}} {{city}}",)
building_number_formats: ElementsType[str] = ("##",)
postcode_formats: ElementsType[str] = ("#####",)
countries: ElementsType[str] = [country.name for country in date_time.Provider.countries]
countries: ElementsType[str] = [
country.name for country in date_time.Provider.countries
]

ALPHA_2 = "alpha-2"
ALPHA_3 = "alpha-3"

alpha_2_country_codes: ElementsType[str] = [country.alpha_2_code for country in date_time.Provider.countries]
alpha_3_country_codes: ElementsType[str] = [country.alpha_3_code for country in date_time.Provider.countries]
alpha_2_country_codes: ElementsType[str] = [
country.alpha_2_code for country in date_time.Provider.countries
]
alpha_3_country_codes: ElementsType[str] = [
country.alpha_3_code for country in date_time.Provider.countries
]

def city_suffix(self) -> str:
"""
Expand Down Expand Up @@ -106,11 +112,17 @@ def current_country(self) -> str:
"""
current_country_code = self.current_country_code()
current_country = [
country.name for country in date_time.Provider.countries if country.alpha_2_code == current_country_code
country.name
for country in date_time.Provider.countries
if country.alpha_2_code == current_country_code
]
if len(current_country) == 1:
return current_country[0] # type: ignore
elif len(current_country) > 1:
raise ValueError(f"Ambiguous country for country code {current_country_code}: {current_country}")
raise ValueError(
f"Ambiguous country for country code {current_country_code}: {current_country}"
)
else:
raise ValueError(f"No appropriate country for country code {current_country_code}")
raise ValueError(
f"No appropriate country for country code {current_country_code}"
)
8 changes: 6 additions & 2 deletions faker/providers/address/bn_BD/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,9 @@ def building_number(self) -> str:
"""
:example: '791' to '৭৯১'
"""
return translate_to_bengali_digits(self.numerify(self.random_element(self.building_number_formats)))
return translate_to_bengali_digits(
self.numerify(self.random_element(self.building_number_formats))
)

def city_prefix(self) -> str:
"""
Expand All @@ -526,7 +528,9 @@ def postcode(self) -> str:
See
https://bdpost.portal.gov.bd/site/page/6aaeabe4-479b-4e5a-a671-e9e5b994bf9a
"""
return translate_to_bengali_digits(self.numerify(self.random_element(self.postcode_formats)))
return translate_to_bengali_digits(
self.numerify(self.random_element(self.postcode_formats))
)

def secondary_address(self) -> str:
"""
Expand Down
4 changes: 3 additions & 1 deletion faker/providers/address/el_GR/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ def line_address(self) -> str:
return self.generator.parse(pattern)

def street_prefix(self) -> str:
return self.random_element(self.street_prefixes_short + self.street_prefixes_long)
return self.random_element(
self.street_prefixes_short + self.street_prefixes_long
)

def street_prefix_short(self) -> str:
return self.random_element(self.street_prefixes_short)
Expand Down
18 changes: 15 additions & 3 deletions faker/providers/address/en_CA/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,15 @@ class Provider(AddressProvider):
"Y",
)

city_prefixes: ElementsType[str] = ("North", "East", "West", "South", "New", "Lake", "Port")
city_prefixes: ElementsType[str] = (
"North",
"East",
"West",
"South",
"New",
"Lake",
"Port",
)

city_suffixes: ElementsType[str] = (
"town",
Expand Down Expand Up @@ -352,7 +360,9 @@ class Provider(AddressProvider):
"{{building_number}} {{street_name}}",
"{{building_number}} {{street_name}} {{secondary_address}}",
)
address_formats = ("{{street_address}}\n{{city}}, {{province_abbr}} {{postalcode}}",)
address_formats = (
"{{street_address}}\n{{city}}, {{province_abbr}} {{postalcode}}",
)
secondary_address_formats = ("Apt. ###", "Suite ###")

def administrative_unit(self) -> str:
Expand Down Expand Up @@ -403,7 +413,9 @@ def postcode_in_province(self, province_abbr: Optional[str] = None) -> str:
postal_code_format: str = self.random_element(self.postal_code_formats)
postal_code_format = postal_code_format.replace(
"?",
self.generator.random_element(self.provinces_postcode_prefixes[province_abbr]),
self.generator.random_element(
self.provinces_postcode_prefixes[province_abbr]
),
1,
)
return self._postcode_replace(postal_code_format)
Expand Down
12 changes: 9 additions & 3 deletions faker/providers/address/en_IN/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,9 @@ def union_territory(self) -> str:

return self.random_element(self.union_territories)[0]

def pincode_in_state(self, state_abbr: Optional[str] = None, include_union_territories: bool = False) -> int:
def pincode_in_state(
self, state_abbr: Optional[str] = None, include_union_territories: bool = False
) -> int:
"""Random PIN Code within provided state abbreviation

:param state_abbr: State Abbr, defaults to None
Expand Down Expand Up @@ -550,10 +552,14 @@ def pincode_in_military(self) -> int:

# Aliases

def zipcode_in_state(self, state_abbr: Optional[str] = None, include_union_territories: bool = False) -> int:
def zipcode_in_state(
self, state_abbr: Optional[str] = None, include_union_territories: bool = False
) -> int:
return self.pincode_in_state(state_abbr, include_union_territories)

def postcode_in_state(self, state_abbr: Optional[str] = None, include_union_territories: bool = False) -> int:
def postcode_in_state(
self, state_abbr: Optional[str] = None, include_union_territories: bool = False
) -> int:
return self.pincode_in_state(state_abbr, include_union_territories)

def pincode_in_army(self) -> int:
Expand Down
8 changes: 6 additions & 2 deletions faker/providers/address/en_MS/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,9 @@ def building_prefix(self) -> str:
def building_number(self) -> str:
return self.bothify(self.random_element(self.building_number_formats))

street_address_formats: ElementsType[str] = ("{{building_prefix}}{{building_number}}, {{street_name}}",)
street_address_formats: ElementsType[str] = (
"{{building_prefix}}{{building_number}}, {{street_name}}",
)

def city_state(self) -> str:
"""Return the complete city address with matching postcode and state
Expand All @@ -443,7 +445,9 @@ def city_state(self) -> str:

# https://en.wikipedia.org/wiki/Addresses_in_Malaysia
# street number, street name, region, and town/city, state.
address_formats = OrderedDict((("{{street_address}}, {{city}}, {{city_state}}", 100.0),))
address_formats = OrderedDict(
(("{{street_address}}, {{city}}, {{city_state}}", 100.0),)
)

def city_prefix(self) -> str:
return self.random_element(self.city_prefixes)
Expand Down
Loading