3

I have a string of a python module stored in a variable (creds) that looks like this:

MY_API_KEY = "DerP12312"
ANOTHER_KEY = "123453)"

(Many more lines than just the 2, but all the same convention)

I'd like to import the values of that module into another class like so:

from creds import MY_API_KEY

A limitation is that I cannot write these contents to local storage. (I'd prefer not to do string disection based on /n and =)

Can I import these values directly from memory?

1 Answer 1

2

Yep, you can use the exec function to execute a string of Python source code (by default it's executed in the current scope so those variables will be set globally):

>>> exec('MY_API_KEY = "DerP12312"\nANOTHER_KEY = "123453)"\n')
>>> MY_API_KEY
'DerP12312'
>>> ANOTHER_KEY
'123453)'
Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly. I control the contents of the imported file, so no concerns about allowing it to exec in code.
Cool. If you control the contents of the file, you might also want to consider using a configuration file format like INI (via configparser).

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.