QA Graphic

Import Faker

Easily add random text to your Python code

Faker is a useful Python package that generates fake data. There's no need to include lots of external text files to generate random data.

#!/usr/local/bin/python3
from faker import Faker
from faker.providers import currency
fake = Faker()
fake.add_provider(currency)
Faker.seed()
for _ in range(10):
	print(fake.pricetag())

Sample Output

$7,604.87
$975.93
$54.21
$89,241.15
$91,565.93
$1,784.08
$6.09
$4,535.13
$22.87
$5.87

Need Same Results?

If you are writing Unit Tests, you may want to have the same list generated. To do this, simply add a value to the seed().

# Keep the same data output:
Faker.seed(10)
# Go random for each run
Faker.seed()

Random Words

Faker has the ability to add random words. In this example, the variable "randomwords" has a list of 20 words, I then shuffle that list and present the winning word of the day:

from faker import Faker
import random
faker = Faker()
randomwords = faker.words(20)
random.shuffle(randomwords)
print(f'Winning Word of the day: {randomwords[1]}')
print(randomwords)

Output:

Winning Word of the day: country
['seven', 'country', 'prove', 'husband', 'cause', 'wide', 'son', 'probably', 'small', 'treatment', 'property', 'policy', 'in', 'along', 'husband', 'cup', 'news', 'partner', 'wish', 'should']

Using Faker Profile

If you need just some of the basic elements of random data, you can use a profile or simpleprofile.

profile() - job, company, ssn, residence, current_location, blood_group, website, username, name, sex, address, mail, birthdate

simple_profile() - username, name, sex, address, mail, birthdate

Exmple Use:

from datetime import date
from datetime import datetime
from dateutil import relativedelta
def mydatecal(someday):
	caldate = relativedelta.relativedelta(datetime.now(),someday );
	myformat = "{} years old".format(caldate.years);
	return myformat
	
customer=fake.simple_profile();
print(customer['name'] + ' has the following email: ' + customer['mail'])
print("Birthday: " + customer['birthdate'].strftime("%B %d, %G"))
print( mydatecal(customer['birthdate']) + " today."+ "n")

Sample Output

Michael Ramos has the following email: russellamy@hotmail.com
Birthday: September 06, 1956
65 years old today.

Installing Faker

Use PIP to install Faker

pip install Faker

If you're not able to install using the pip command, use this:

python3 -m pip install faker --user