You can inherit the BaseProvider class and define your custom functions. Afterwards you can add it to a Faker object.
There are two possible options:
1. Retrieve factory Faker object from factory library and add custom provider.
In this scenario you retrieve the instantiated Faker object from the factory library using a private get method. Please note, it is bad practice to access private methods outside of a class.
import factory
from faker import providers
class HelloWorldProvider(providers.BaseProvider):
"""Use provider to generate `hello world`."""
def hello_world(self) -> str:
"""Say hello to the world"""
return "hello world"
factory.Faker.add_provider(HelloWorldProvider)
fake = factory.Faker._get_faker()
print(fake.hello_world())
2. Instantiate new Faker object and add custom provider
With this option you achieve the same result without accessing any private methods outside of the class. I would advise on this course of action.
import faker
fake = faker.Faker()
class HelloWorldProvider(faker.providers.BaseProvider):
"""Use provider to generate `hello world`."""
def hello_world(self) -> str:
"""Say hello to the world"""
return "hello world"
fake.add_provider(HelloWorldProvider)
print(fake.hello_world())
Faker BaseProvider reference