0

I want a function to set the random seeds for several known packages.I'd like to create a library function which calls:

tf.set_random_seed(seed)
np.random.seed(seed)
random.seed(seed)

, but only if actually needed. In some cases the caller will be part of a program that uses numpy and in others it won't.

I want a single function, in its own importable file, which will set the random seed of various packages, but not to import the package unless used by the caller.

I can easily work-around this by inserting the method in each caller's file. But, I'm curious if there is a way to do what I want to do.

Can I somehow query the calling function and determine "In your scope, has numpy been imported"? If so, this function would call np.random.seed.

2
  • 2
    There is an answer in this question related to checking imports of a module from outside of that module: stackoverflow.com/questions/4858100/… Commented Jan 9, 2019 at 20:39
  • Perfect. I'll write it out as an answer. Commented Jan 9, 2019 at 21:23

1 Answer 1

2

@Luke DeLuccia pointed me in the correct direction. For future readers, The code might look something like this:

import sys
def set_pseudoseeds(seed):
    # random
    try:
        module = sys.modules['random']
    except KeyError:
        pass
    else:
        module.seed(seed)
    ...

Thanks Luke!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.