We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Refactor Profile to be used with locale: how
I got this idea but i'm not sure it would be the simplest: the actual profile.py becomes something like "internal_profile.py", its methods are renamed "internal_simple_profile()" and "internal_profile()", and is removed from the list of standard providers. Then we will have a standard profile.py that simply calls self.generator.internal_profile(). For each locale instead, we will be able to add more logic, for example to customize field names and eventually values. 

Do you think there would be a simpler way to do it?


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `setup.py`
Content:
```
1 #!/usr/bin/env python
2 # coding=utf-8
3 
4 import os
5 import io
6 
7 from setuptools import setup, find_packages
8 
9 here = os.path.abspath(os.path.dirname(__file__))
10 README = io.open(os.path.join(here, 'README.rst'), encoding="utf8").read()
11 
12 
13 version = '0.7.18'
14 
15 # this module can be zip-safe if the zipimporter implements iter_modules or if
16 # pkgutil.iter_importer_modules has registered a dispatch for the zipimporter.
17 try:
18     import pkgutil
19     import zipimport
20     zip_safe = hasattr(zipimport.zipimporter, "iter_modules") or \
21         zipimport.zipimporter in pkgutil.iter_importer_modules.registry.keys()
22 except (ImportError, AttributeError):
23     zip_safe = False
24 
25 setup(
26     name='Faker',
27     version=version,
28     description="Faker is a Python package that generates fake data for you.",
29     long_description=README,
30     entry_points={
31         'console_scripts': ['faker=faker.cli:execute_from_command_line'],
32     },
33     classifiers=[
34         # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
35         'Development Status :: 3 - Alpha',
36         'Environment :: Console',
37         'Intended Audience :: Developers',
38         'Programming Language :: Python',
39         'Programming Language :: Python :: 2',
40         'Programming Language :: Python :: 2.7',
41         'Programming Language :: Python :: 3',
42         'Programming Language :: Python :: 3.3',
43         'Programming Language :: Python :: 3.4',
44         'Programming Language :: Python :: 3.5',
45         'Programming Language :: Python :: 3.6',
46         'Programming Language :: Python :: Implementation :: CPython',
47         'Programming Language :: Python :: Implementation :: PyPy',
48         'Topic :: Software Development :: Libraries :: Python Modules',
49         'Topic :: Software Development :: Testing',
50         'Topic :: Utilities',
51         'License :: OSI Approved :: MIT License'
52     ],
53     keywords='faker fixtures data test mock generator',
54     author='joke2k',
55     author_email='joke2k@gmail.com',
56     url='https://github.com/joke2k/faker',
57     license='MIT License',
58     packages=find_packages(exclude=["docs", "tests", "tests.*"]),
59     platforms=["any"],
60     test_suite='tests',
61     zip_safe=zip_safe,
62     install_requires=[
63         "python-dateutil>=2.4",
64         "six",
65     ],
66     extras_require={
67         ':python_version=="2.7"': [
68             'ipaddress',
69         ],
70         ':python_version=="3.0"': [
71             'importlib',
72         ],
73         ':python_version=="3.2"': [
74             'ipaddress',
75         ],
76     }
77 )
78
```

Path: `faker/generator.py`
Content:
```
1 # coding=utf-8
2 
3 from __future__ import unicode_literals
4 
5 import re
6 import random
7 
8 
9 _re_token = re.compile(r'\{\{(\s?)(\w+)(\s?)\}\}')
10 random = random.Random()
11 
12 
13 class Generator(object):
14 
15     __config = {}
16 
17     def __init__(self, **config):
18         self.providers = []
19         self.__config = dict(
20             list(self.__config.items()) + list(config.items()))
21 
22     def add_provider(self, provider):
23 
24         if type(provider) is type:
25             provider = provider(self)
26 
27         self.providers.insert(0, provider)
28 
29         for method_name in dir(provider):
30             # skip 'private' method
31             if method_name.startswith('_'):
32                 continue
33 
34             faker_function = getattr(provider, method_name)
35 
36             if hasattr(faker_function, '__call__') or \
37                     isinstance(faker_function, (classmethod, staticmethod)):
38                 # add all faker method to generator
39                 self.set_formatter(method_name, faker_function)
40 
41     def provider(self, name):
42         try:
43             lst = [p for p in self.get_providers()
44                    if p.__provider__ == name.lower()]
45             return lst[0]
46         except IndexError:
47             return None
48 
49     def get_providers(self):
50         """Returns added providers."""
51         return self.providers
52 
53     @property
54     def random(self):
55         return random
56 
57     def seed(self, seed=None):
58         """Calls random.seed"""
59         random.seed(seed)
60 
61     def format(self, formatter, *args, **kwargs):
62         """
63         This is a secure way to make a fake from another Provider.
64         """
65         # TODO: data export?
66         return self.get_formatter(formatter)(*args, **kwargs)
67 
68     def get_formatter(self, formatter):
69         try:
70             return getattr(self, formatter)
71         except AttributeError:
72             raise AttributeError('Unknown formatter "{0}"'.format(formatter))
73 
74     def set_formatter(self, name, method):
75         """
76         This method adds a provider method to generator.
77         Override this method to add some decoration or logging stuff.
78         """
79         setattr(self, name, method)
80 
81     def parse(self, text):
82         """
83         Replaces tokens (like '{{ tokenName }}' or '{{tokenName}}')
84         with the result from the token method call.
85         """
86         return _re_token.sub(self.__format_token, text)
87 
88     def __format_token(self, matches):
89         formatter = list(matches.groups())
90         formatter[1] = self.format(formatter[1])
91         return ''.join(formatter)
92
```

Path: `faker/factory.py`
Content:
```
1 # coding=utf-8
2 
3 from __future__ import unicode_literals
4 from __future__ import absolute_import
5 
6 from importlib import import_module
7 import locale as pylocale
8 
9 from faker import Generator
10 from faker.config import DEFAULT_LOCALE, PROVIDERS, AVAILABLE_LOCALES
11 from faker.utils.loading import list_module
12 
13 
14 class Factory(object):
15 
16     @classmethod
17     def create(cls, locale=None, providers=None, generator=None, includes=None, **config):
18         if includes is None:
19             includes = []
20 
21         # fix locale to package name
22         locale = locale.replace('-', '_') if locale else DEFAULT_LOCALE
23         locale = pylocale.normalize(locale).split('.')[0]
24         if locale not in AVAILABLE_LOCALES:
25             msg = 'Invalid configuration for faker locale "{0}"'.format(locale)
26             raise AttributeError(msg)
27 
28         providers = providers or PROVIDERS
29 
30         providers += includes
31 
32         faker = generator or Generator(**config)
33 
34         for prov_name in providers:
35             if prov_name == 'faker.providers':
36                 continue
37 
38             prov_cls, lang_found = cls._get_provider_class(prov_name, locale)
39             provider = prov_cls(faker)
40             provider.__provider__ = prov_name
41             provider.__lang__ = lang_found
42             faker.add_provider(provider)
43 
44         return faker
45 
46     @classmethod
47     def _get_provider_class(cls, provider, locale=''):
48 
49         provider_class = cls._find_provider_class(provider, locale)
50 
51         if provider_class:
52             return provider_class, locale
53 
54         if locale and locale != DEFAULT_LOCALE:
55             # fallback to default locale
56             provider_class = cls._find_provider_class(provider, DEFAULT_LOCALE)
57             if provider_class:
58                 return provider_class, DEFAULT_LOCALE
59 
60         # fallback to no locale
61         provider_class = cls._find_provider_class(provider)
62         if provider_class:
63             return provider_class, None
64 
65         msg = 'Unable to find provider "{0}" with locale "{1}"'.format(
66             provider, locale)
67         raise ValueError(msg)
68 
69     @classmethod
70     def _find_provider_class(cls, provider_path, locale=None):
71         provider_module = import_module(provider_path)
72 
73         if getattr(provider_module, 'localized', False):
74             available_locales = list_module(provider_module)
75             if not locale or locale not in available_locales:
76                 locale = getattr(provider_module, 'default_locale', DEFAULT_LOCALE)
77 
78             path = "{provider_path}.{locale}".format(
79                 provider_path=provider_path,
80                 locale=locale,
81             )
82             provider_module = import_module(path)
83         else:
84             if locale is not None:
85                 provider_module = import_module(provider_path)
86 
87         return provider_module.Provider
88
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/faker/factory.py b/faker/factory.py
--- a/faker/factory.py
+++ b/faker/factory.py
@@ -25,6 +25,7 @@
             msg = 'Invalid configuration for faker locale "{0}"'.format(locale)
             raise AttributeError(msg)
 
+        config['locale'] = locale
         providers = providers or PROVIDERS
 
         providers += includes
diff --git a/faker/generator.py b/faker/generator.py
--- a/faker/generator.py
+++ b/faker/generator.py
@@ -69,7 +69,15 @@
         try:
             return getattr(self, formatter)
         except AttributeError:
-            raise AttributeError('Unknown formatter "{0}"'.format(formatter))
+            if 'locale' in self.__config:
+                msg = 'Unknown formatter "{0}" with locale "{1}"'.format(
+                    formatter, self.__config['locale']
+                )
+            else:
+                raise AttributeError('Unknown formatter "{0}"'.format(
+                    formatter
+                ))
+            raise AttributeError(msg)
 
     def set_formatter(self, name, method):
         """
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -60,8 +60,10 @@
     test_suite='tests',
     zip_safe=zip_safe,
     install_requires=[
+        "email_validator>=1.0.2",
         "python-dateutil>=2.4",
         "six",
+        "ukpostcodeparser>=1.1.1",
     ],
     extras_require={
         ':python_version=="2.7"': [

{"golden_diff": "diff --git a/faker/factory.py b/faker/factory.py\n--- a/faker/factory.py\n+++ b/faker/factory.py\n@@ -25,6 +25,7 @@\n             msg = 'Invalid configuration for faker locale \"{0}\"'.format(locale)\n             raise AttributeError(msg)\n \n+        config['locale'] = locale\n         providers = providers or PROVIDERS\n \n         providers += includes\ndiff --git a/faker/generator.py b/faker/generator.py\n--- a/faker/generator.py\n+++ b/faker/generator.py\n@@ -69,7 +69,15 @@\n         try:\n             return getattr(self, formatter)\n         except AttributeError:\n-            raise AttributeError('Unknown formatter \"{0}\"'.format(formatter))\n+            if 'locale' in self.__config:\n+                msg = 'Unknown formatter \"{0}\" with locale \"{1}\"'.format(\n+                    formatter, self.__config['locale']\n+                )\n+            else:\n+                raise AttributeError('Unknown formatter \"{0}\"'.format(\n+                    formatter\n+                ))\n+            raise AttributeError(msg)\n \n     def set_formatter(self, name, method):\n         \"\"\"\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -60,8 +60,10 @@\n     test_suite='tests',\n     zip_safe=zip_safe,\n     install_requires=[\n+        \"email_validator>=1.0.2\",\n         \"python-dateutil>=2.4\",\n         \"six\",\n+        \"ukpostcodeparser>=1.1.1\",\n     ],\n     extras_require={\n         ':python_version==\"2.7\"': [\n", "issue": "Refactor Profile to be used with locale: how\nI got this idea but i'm not sure it would be the simplest: the actual profile.py becomes something like \"internal_profile.py\", its methods are renamed \"internal_simple_profile()\" and \"internal_profile()\", and is removed from the list of standard providers. Then we will have a standard profile.py that simply calls self.generator.internal_profile(). For each locale instead, we will be able to add more logic, for example to customize field names and eventually values. \n\nDo you think there would be a simpler way to do it?\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# coding=utf-8\n\nimport os\nimport io\n\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = io.open(os.path.join(here, 'README.rst'), encoding=\"utf8\").read()\n\n\nversion = '0.7.18'\n\n# this module can be zip-safe if the zipimporter implements iter_modules or if\n# pkgutil.iter_importer_modules has registered a dispatch for the zipimporter.\ntry:\n    import pkgutil\n    import zipimport\n    zip_safe = hasattr(zipimport.zipimporter, \"iter_modules\") or \\\n        zipimport.zipimporter in pkgutil.iter_importer_modules.registry.keys()\nexcept (ImportError, AttributeError):\n    zip_safe = False\n\nsetup(\n    name='Faker',\n    version=version,\n    description=\"Faker is a Python package that generates fake data for you.\",\n    long_description=README,\n    entry_points={\n        'console_scripts': ['faker=faker.cli:execute_from_command_line'],\n    },\n    classifiers=[\n        # See https://pypi.python.org/pypi?%3Aaction=list_classifiers\n        'Development Status :: 3 - Alpha',\n        'Environment :: Console',\n        'Intended Audience :: Developers',\n        'Programming Language :: Python',\n        'Programming Language :: Python :: 2',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.3',\n        'Programming Language :: Python :: 3.4',\n        'Programming Language :: Python :: 3.5',\n        'Programming Language :: Python :: 3.6',\n        'Programming Language :: Python :: Implementation :: CPython',\n        'Programming Language :: Python :: Implementation :: PyPy',\n        'Topic :: Software Development :: Libraries :: Python Modules',\n        'Topic :: Software Development :: Testing',\n        'Topic :: Utilities',\n        'License :: OSI Approved :: MIT License'\n    ],\n    keywords='faker fixtures data test mock generator',\n    author='joke2k',\n    author_email='joke2k@gmail.com',\n    url='https://github.com/joke2k/faker',\n    license='MIT License',\n    packages=find_packages(exclude=[\"docs\", \"tests\", \"tests.*\"]),\n    platforms=[\"any\"],\n    test_suite='tests',\n    zip_safe=zip_safe,\n    install_requires=[\n        \"python-dateutil>=2.4\",\n        \"six\",\n    ],\n    extras_require={\n        ':python_version==\"2.7\"': [\n            'ipaddress',\n        ],\n        ':python_version==\"3.0\"': [\n            'importlib',\n        ],\n        ':python_version==\"3.2\"': [\n            'ipaddress',\n        ],\n    }\n)\n", "path": "setup.py"}, {"content": "# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nimport re\nimport random\n\n\n_re_token = re.compile(r'\\{\\{(\\s?)(\\w+)(\\s?)\\}\\}')\nrandom = random.Random()\n\n\nclass Generator(object):\n\n    __config = {}\n\n    def __init__(self, **config):\n        self.providers = []\n        self.__config = dict(\n            list(self.__config.items()) + list(config.items()))\n\n    def add_provider(self, provider):\n\n        if type(provider) is type:\n            provider = provider(self)\n\n        self.providers.insert(0, provider)\n\n        for method_name in dir(provider):\n            # skip 'private' method\n            if method_name.startswith('_'):\n                continue\n\n            faker_function = getattr(provider, method_name)\n\n            if hasattr(faker_function, '__call__') or \\\n                    isinstance(faker_function, (classmethod, staticmethod)):\n                # add all faker method to generator\n                self.set_formatter(method_name, faker_function)\n\n    def provider(self, name):\n        try:\n            lst = [p for p in self.get_providers()\n                   if p.__provider__ == name.lower()]\n            return lst[0]\n        except IndexError:\n            return None\n\n    def get_providers(self):\n        \"\"\"Returns added providers.\"\"\"\n        return self.providers\n\n    @property\n    def random(self):\n        return random\n\n    def seed(self, seed=None):\n        \"\"\"Calls random.seed\"\"\"\n        random.seed(seed)\n\n    def format(self, formatter, *args, **kwargs):\n        \"\"\"\n        This is a secure way to make a fake from another Provider.\n        \"\"\"\n        # TODO: data export?\n        return self.get_formatter(formatter)(*args, **kwargs)\n\n    def get_formatter(self, formatter):\n        try:\n            return getattr(self, formatter)\n        except AttributeError:\n            raise AttributeError('Unknown formatter \"{0}\"'.format(formatter))\n\n    def set_formatter(self, name, method):\n        \"\"\"\n        This method adds a provider method to generator.\n        Override this method to add some decoration or logging stuff.\n        \"\"\"\n        setattr(self, name, method)\n\n    def parse(self, text):\n        \"\"\"\n        Replaces tokens (like '{{ tokenName }}' or '{{tokenName}}')\n        with the result from the token method call.\n        \"\"\"\n        return _re_token.sub(self.__format_token, text)\n\n    def __format_token(self, matches):\n        formatter = list(matches.groups())\n        formatter[1] = self.format(formatter[1])\n        return ''.join(formatter)\n", "path": "faker/generator.py"}, {"content": "# coding=utf-8\n\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nfrom importlib import import_module\nimport locale as pylocale\n\nfrom faker import Generator\nfrom faker.config import DEFAULT_LOCALE, PROVIDERS, AVAILABLE_LOCALES\nfrom faker.utils.loading import list_module\n\n\nclass Factory(object):\n\n    @classmethod\n    def create(cls, locale=None, providers=None, generator=None, includes=None, **config):\n        if includes is None:\n            includes = []\n\n        # fix locale to package name\n        locale = locale.replace('-', '_') if locale else DEFAULT_LOCALE\n        locale = pylocale.normalize(locale).split('.')[0]\n        if locale not in AVAILABLE_LOCALES:\n            msg = 'Invalid configuration for faker locale \"{0}\"'.format(locale)\n            raise AttributeError(msg)\n\n        providers = providers or PROVIDERS\n\n        providers += includes\n\n        faker = generator or Generator(**config)\n\n        for prov_name in providers:\n            if prov_name == 'faker.providers':\n                continue\n\n            prov_cls, lang_found = cls._get_provider_class(prov_name, locale)\n            provider = prov_cls(faker)\n            provider.__provider__ = prov_name\n            provider.__lang__ = lang_found\n            faker.add_provider(provider)\n\n        return faker\n\n    @classmethod\n    def _get_provider_class(cls, provider, locale=''):\n\n        provider_class = cls._find_provider_class(provider, locale)\n\n        if provider_class:\n            return provider_class, locale\n\n        if locale and locale != DEFAULT_LOCALE:\n            # fallback to default locale\n            provider_class = cls._find_provider_class(provider, DEFAULT_LOCALE)\n            if provider_class:\n                return provider_class, DEFAULT_LOCALE\n\n        # fallback to no locale\n        provider_class = cls._find_provider_class(provider)\n        if provider_class:\n            return provider_class, None\n\n        msg = 'Unable to find provider \"{0}\" with locale \"{1}\"'.format(\n            provider, locale)\n        raise ValueError(msg)\n\n    @classmethod\n    def _find_provider_class(cls, provider_path, locale=None):\n        provider_module = import_module(provider_path)\n\n        if getattr(provider_module, 'localized', False):\n            available_locales = list_module(provider_module)\n            if not locale or locale not in available_locales:\n                locale = getattr(provider_module, 'default_locale', DEFAULT_LOCALE)\n\n            path = \"{provider_path}.{locale}\".format(\n                provider_path=provider_path,\n                locale=locale,\n            )\n            provider_module = import_module(path)\n        else:\n            if locale is not None:\n                provider_module = import_module(provider_path)\n\n        return provider_module.Provider\n", "path": "faker/factory.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# coding=utf-8\n\nimport os\nimport io\n\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = io.open(os.path.join(here, 'README.rst'), encoding=\"utf8\").read()\n\n\nversion = '0.7.18'\n\n# this module can be zip-safe if the zipimporter implements iter_modules or if\n# pkgutil.iter_importer_modules has registered a dispatch for the zipimporter.\ntry:\n    import pkgutil\n    import zipimport\n    zip_safe = hasattr(zipimport.zipimporter, \"iter_modules\") or \\\n        zipimport.zipimporter in pkgutil.iter_importer_modules.registry.keys()\nexcept (ImportError, AttributeError):\n    zip_safe = False\n\nsetup(\n    name='Faker',\n    version=version,\n    description=\"Faker is a Python package that generates fake data for you.\",\n    long_description=README,\n    entry_points={\n        'console_scripts': ['faker=faker.cli:execute_from_command_line'],\n    },\n    classifiers=[\n        # See https://pypi.python.org/pypi?%3Aaction=list_classifiers\n        'Development Status :: 3 - Alpha',\n        'Environment :: Console',\n        'Intended Audience :: Developers',\n        'Programming Language :: Python',\n        'Programming Language :: Python :: 2',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.3',\n        'Programming Language :: Python :: 3.4',\n        'Programming Language :: Python :: 3.5',\n        'Programming Language :: Python :: 3.6',\n        'Programming Language :: Python :: Implementation :: CPython',\n        'Programming Language :: Python :: Implementation :: PyPy',\n        'Topic :: Software Development :: Libraries :: Python Modules',\n        'Topic :: Software Development :: Testing',\n        'Topic :: Utilities',\n        'License :: OSI Approved :: MIT License'\n    ],\n    keywords='faker fixtures data test mock generator',\n    author='joke2k',\n    author_email='joke2k@gmail.com',\n    url='https://github.com/joke2k/faker',\n    license='MIT License',\n    packages=find_packages(exclude=[\"docs\", \"tests\", \"tests.*\"]),\n    platforms=[\"any\"],\n    test_suite='tests',\n    zip_safe=zip_safe,\n    install_requires=[\n        \"email_validator>=1.0.2\",\n        \"python-dateutil>=2.4\",\n        \"six\",\n        \"ukpostcodeparser>=1.1.1\",\n    ],\n    extras_require={\n        ':python_version==\"2.7\"': [\n            'ipaddress',\n        ],\n        ':python_version==\"3.0\"': [\n            'importlib',\n        ],\n        ':python_version==\"3.2\"': [\n            'ipaddress',\n        ],\n    }\n)\n", "path": "setup.py"}, {"content": "# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nimport re\nimport random\n\n\n_re_token = re.compile(r'\\{\\{(\\s?)(\\w+)(\\s?)\\}\\}')\nrandom = random.Random()\n\n\nclass Generator(object):\n\n    __config = {}\n\n    def __init__(self, **config):\n        self.providers = []\n        self.__config = dict(\n            list(self.__config.items()) + list(config.items()))\n\n    def add_provider(self, provider):\n\n        if type(provider) is type:\n            provider = provider(self)\n\n        self.providers.insert(0, provider)\n\n        for method_name in dir(provider):\n            # skip 'private' method\n            if method_name.startswith('_'):\n                continue\n\n            faker_function = getattr(provider, method_name)\n\n            if hasattr(faker_function, '__call__') or \\\n                    isinstance(faker_function, (classmethod, staticmethod)):\n                # add all faker method to generator\n                self.set_formatter(method_name, faker_function)\n\n    def provider(self, name):\n        try:\n            lst = [p for p in self.get_providers()\n                   if p.__provider__ == name.lower()]\n            return lst[0]\n        except IndexError:\n            return None\n\n    def get_providers(self):\n        \"\"\"Returns added providers.\"\"\"\n        return self.providers\n\n    @property\n    def random(self):\n        return random\n\n    def seed(self, seed=None):\n        \"\"\"Calls random.seed\"\"\"\n        random.seed(seed)\n\n    def format(self, formatter, *args, **kwargs):\n        \"\"\"\n        This is a secure way to make a fake from another Provider.\n        \"\"\"\n        # TODO: data export?\n        return self.get_formatter(formatter)(*args, **kwargs)\n\n    def get_formatter(self, formatter):\n        try:\n            return getattr(self, formatter)\n        except AttributeError:\n            if 'locale' in self.__config:\n                msg = 'Unknown formatter \"{0}\" with locale \"{1}\"'.format(\n                    formatter, self.__config['locale']\n                )\n            else:\n                raise AttributeError('Unknown formatter \"{0}\"'.format(\n                    formatter\n                ))\n            raise AttributeError(msg)\n\n    def set_formatter(self, name, method):\n        \"\"\"\n        This method adds a provider method to generator.\n        Override this method to add some decoration or logging stuff.\n        \"\"\"\n        setattr(self, name, method)\n\n    def parse(self, text):\n        \"\"\"\n        Replaces tokens (like '{{ tokenName }}' or '{{tokenName}}')\n        with the result from the token method call.\n        \"\"\"\n        return _re_token.sub(self.__format_token, text)\n\n    def __format_token(self, matches):\n        formatter = list(matches.groups())\n        formatter[1] = self.format(formatter[1])\n        return ''.join(formatter)\n", "path": "faker/generator.py"}, {"content": "# coding=utf-8\n\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nfrom importlib import import_module\nimport locale as pylocale\n\nfrom faker import Generator\nfrom faker.config import DEFAULT_LOCALE, PROVIDERS, AVAILABLE_LOCALES\nfrom faker.utils.loading import list_module\n\n\nclass Factory(object):\n\n    @classmethod\n    def create(cls, locale=None, providers=None, generator=None, includes=None, **config):\n        if includes is None:\n            includes = []\n\n        # fix locale to package name\n        locale = locale.replace('-', '_') if locale else DEFAULT_LOCALE\n        locale = pylocale.normalize(locale).split('.')[0]\n        if locale not in AVAILABLE_LOCALES:\n            msg = 'Invalid configuration for faker locale \"{0}\"'.format(locale)\n            raise AttributeError(msg)\n\n        config['locale'] = locale\n        providers = providers or PROVIDERS\n\n        providers += includes\n\n        faker = generator or Generator(**config)\n\n        for prov_name in providers:\n            if prov_name == 'faker.providers':\n                continue\n\n            prov_cls, lang_found = cls._get_provider_class(prov_name, locale)\n            provider = prov_cls(faker)\n            provider.__provider__ = prov_name\n            provider.__lang__ = lang_found\n            faker.add_provider(provider)\n\n        return faker\n\n    @classmethod\n    def _get_provider_class(cls, provider, locale=''):\n\n        provider_class = cls._find_provider_class(provider, locale)\n\n        if provider_class:\n            return provider_class, locale\n\n        if locale and locale != DEFAULT_LOCALE:\n            # fallback to default locale\n            provider_class = cls._find_provider_class(provider, DEFAULT_LOCALE)\n            if provider_class:\n                return provider_class, DEFAULT_LOCALE\n\n        # fallback to no locale\n        provider_class = cls._find_provider_class(provider)\n        if provider_class:\n            return provider_class, None\n\n        msg = 'Unable to find provider \"{0}\" with locale \"{1}\"'.format(\n            provider, locale)\n        raise ValueError(msg)\n\n    @classmethod\n    def _find_provider_class(cls, provider_path, locale=None):\n        provider_module = import_module(provider_path)\n\n        if getattr(provider_module, 'localized', False):\n            available_locales = list_module(provider_module)\n            if not locale or locale not in available_locales:\n                locale = getattr(provider_module, 'default_locale', DEFAULT_LOCALE)\n\n            path = \"{provider_path}.{locale}\".format(\n                provider_path=provider_path,\n                locale=locale,\n            )\n            provider_module = import_module(path)\n        else:\n            if locale is not None:\n                provider_module = import_module(provider_path)\n\n        return provider_module.Provider\n", "path": "faker/factory.py"}]}