Package: rand
randRandom generated String from regex patternWARNINGThe libraryrandis still in working-in-progress. It is subject to high possibility of API changes. Would appreciate feedback, suggestions or help.Why?There are lot of existing projects similar torand, they are powerful and have similar goals and results. However most of them are old projects/non-maintained and non-MIT licenses.This is a good opportunity forrandto be the library to help generate random data for any projects and gather all other existing libraries to be the main driver.InstallUse pip or clone this repository and execute the setup.py file.$pipinstallrandUsagesBasic usagerandexamples# import modulefromrandimportRand# initialise objectrnd=Rand()# generate pattern literalrnd.gen('koro')# ['koro']rnd.gen('28')# ['28']rnd.gen('a-z')# ['a-z']# generate pattern anyrnd.gen('.')# any char in string.printable# generate pattern branchrnd.gen('ko|ro')# either ['ko'] or ['ro']rnd.gen('ko|ro|ro')# either ['ko'] or ['ro']# generate pattern inrnd.gen('[kororo]')# either ['k'] or ['o'] or ['r']rnd.gen('k[o]r[o]r[o]')# ['kororo']# generate pattern repeatrnd.gen('r{2,8}')# char r in length between 2 to 8 times# generate pattern rangernd.gen('[a-z]')# char between a to z# generate pattern subpatternrnd.gen('(ro)')# ['ro']ProvidersThe libraryrandat core only provide random generators based on regex. Providers are built to allow extensions for rand.Built-in ProvidersThere are a few built-in providers insiderandEN ProviderThis library covers most usage around English requirements.fromrandimportRandrnd=Rand()rnd.gen('(:en_vocal:)')# char either a, i, u, e, oDataset ProviderThis library helps on getting data from dataset such as Python object or Database withpeewee.fromrandimportRandfromrand.providers.dsimportRandDatasetBaseProvider,ListDatasetTarget# example using dict of listdb={'names':['test1','test1'],'cities':['test2','test2']}ds=RandDatasetBaseProvider(prefix='ds',target=ListDatasetTarget(db=db))rnd=Rand()rnd.register_provider(ds)rnd.gen('(:ds_get:)',['names'])# ['test1']rnd.gen('(:ds_get:)',['cities'])# ['test2']# or, magic getattrrnd.gen('(:ds_get_names:)-(:ds_get_cities:)')# ['test1-test2']# example of database using peeweefrompeeweeimportProxyfromplayhouse.sqlite_extimportCSqliteExtDatabasefromrand.providers.dsimportRandDatasetBaseProvider,DBDatasetTargetdb=Proxy()# ensure to have table with name "names", contains column at least (id, name)db.initialize(CSqliteExtDatabase(':memory:',bloomfilter=True))ds=RandDatasetBaseProvider(prefix='ds',target=DBDatasetTarget(db=db))rnd=Rand()rnd.register_provider(ds)rnd.gen('(:ds_get:)',['names'])# ['test']db.close()Integration ProvidersThe libraryrandalso has integration with existing projects such as Faker. Ensure you have faker library installed.FakerThere is super basic integration with Faker for now, soon will be more implemented.# ensure you have Faker installedpipinstallFakerfromrandimportRandrnd=Rand()rnd.gen('(:faker_hexify:)')# abcCustom ParseExtending rand is simple, there are register_parse and register_provider, both of this has special level of customisation.Simple Register ParseThis is example of creating custom parse in simple way.fromrandimportRand# init rand classrnd=Rand()# the definitiondefparse_test1(pattern,opts=None):return'test1'# the registrationrnd.register_parse(name='test1',fn=parse_test1)# test itrnd.gen('(:test1:)')Decorator Wrapper Register ParseThis is faster way with decorator pattern to register custom parse.fromrandimportRand# init rand classrnd=Rand()# the definition@rnd.register_parse_wrapper(name='test1')defparse_test1(pattern,opts=None):return'test1'# test itrnd.gen('(:test1:)')Custom ProvidersCustom provider is upper level customisation inrand, it behaves quite differently than custom parseSimple Register ProviderBelow is sample code on how to integrate an existing class definition (TestProxy) to Rand.fromrand.providers.baseimportRandBaseProviderfromrandimportRandclassTestProvider(RandBaseProvider):def_parse_fn(self,pattern,opts=None):return'test'defparse(self,name:str,pattern:any,opts:dict):# name always start with _parse_[PREFIX], normalise firstparsed_name=self.get_parse_name(name)ifparsed_name:returnself._parse_fn(pattern,opts)returnNone# init rand classrnd=Rand()rnd.register_provider(TestProvider(prefix='test_fn'))assertrnd.gen('(:test_fn:)')=='test'fromrandimportRandfromrand.providers.baseimportRandProxyBaseProvider# class definitionclassTestProxy:# simple function definition to return args valuesdeftarget(self,arg1='def1',arg2='def2'):return'%s-%s'%(arg1,arg2)# init rand classrnd=Rand()# create proxy provider helper and register to randtest_proxy=RandProxyBaseProvider(prefix='test',target=TestProxy())rnd.register_provider(test_proxy)# testprint(rnd.gen('(:test_target:)'))# ['def1-def2']print(rnd.gen('(:test_target:)',['ok1']))# ['ok1-def2']print(rnd.gen('(:test_target:)',['ok1','ok2']))# ['ok1-def2']print(rnd.gen('(:test_target:)',[['ok1','ok2']]))# ['ok1-ok2']print(rnd.gen('(:test_target:)',[['ok1','ok2'],'ok3']))# ['ok1-ok2']print(rnd.gen('(:test_target:)',[{'arg1':'ok1'}]))# ['ok1-def2']print(rnd.gen('(:test_target:)',[{'arg1':'ok1','arg2':'ok2'}]))# ['ok1-ok2']Decorator Wrapper Register ProviderThis is faster way with decorator pattern to register custom provider.fromrandimportRand# init rand classrnd=Rand()@rnd.register_provider_fn_wrapper(prefix='test2')defparse_test2(pattern,opts=None):return'test2'print(rnd.gen('(:test2:)'))# 'test2'Different Between Custom Parser and ProviderThe wayrandworks, register_parse taps into the core ofrand, following the token from sre_parse, when the definition is returned,
it is possible to return sre_parse token with existing token name or custom token which points to the custom definition.fromrandimportRand# init rand classrnd=Rand()@rnd.register_parse_wrapper(name='test1')defparse_test1(pattern,opts=None):return'test1'@rnd.register_parse_wrapper(name='test2')defparse_test2(pattern,opts=None):returnrnd.sre_parse_compile_parse('(:test1:)')print(rnd.gen('(:test2:)'))# 'test1'TestRun test by installing packages and run tox$pipinstallpoetrytox
$tox
$tox-epy36--tests/test_ds.pyFor hot-reload development coding$npmi-gnodemon
$nodemon-wrand--execpython-c"from rand import Rand"Help?Any feedback, suggestions and integration with 3rd-party libraries can be added using PR or create issues if needed helps.Similar ProjectsList of projects similar torand:exrex: Irregular methods on regular expressionsxeger: Library to generate random strings from regular expressionsstrgen: A Python module for a template language that generates randomized dataAcknowdlge ProjectsList of projects thatranddepends on:peewee: a small, expressive orm -- supports postgresql, mysql and sqlitepytest: The pytest framework makes it easy to write small tests, yet scales to support complex functional testingcoverage: Code coverage measurement for Pythonpytest-cov: Coverage plugin for pytest