Random with Seed in Python

MattMMattM Posts: 2
edited February 11, 2016 6:57AM in SQL Data Generator
I would like to use the config["seed"] inside a python script.
I want to be able to generate the same random number sequence and use it in the script each time.
I want the numbers different for each line, but the same for each execution.

But I can't seed the Random function in the correct way.

I've started with this ...

# Basic generator template
from System import Random
import datetime
#random = Random(config["seed"]) #Can't configure random outside of main because config has no scope here

def main(config):
# config["column_name"] is the column name
# config["column_type"] is the column datatype
# config["column_size"] is the column size
# config["n_rows"] is the number of rows
# config["seed"] is the current random seed

random = Random(config["seed"]) #If I configure it here it gives me the same number for every data row
#random = Random() # if I enable this line I get random numbers, but they aren't reproducable - they are different for every execution

adddays = random.Next(365)
newdt = datetime.datetime.now() + datetime.timedelta(days=adddays)

return newdt


Can someone point me in the correct direction?

Comments

  • Hi Matt,

    The approach I've taken is to make random a global variable and to seed it only once when the generator is on the first row. This produces repeatable results.
    from System import Random
    import datetime
    
    def main(config):
        # config["column_name"] is the column name
        # config["column_type"] is the column datatype
        # config["column_size"] is the column size
        # config["n_rows"] is the number of rows
        # config["seed"] is the current random seed
        if (config["row_count"] == 0):
            global random
            random = Random(config["seed"])
        adddays = random.Next(365)
        newdt = datetime.datetime.now() + datetime.timedelta(days=adddays)
        return newdt
    

    I hope this helps.
    Software Engineer
    Redgate Software
Sign In or Register to comment.