1

I have set a variable x="hii!!" in another file called ImporterFile.py. I thought pre-defining the variable x and then re-importing it would work, but it didn't.

from ImporterFile import x

def grab(string):
    from ImporterFile import (string)

grab(x)

The original problem was that when running the file it would say that "string" wasn't a variable that existed in that file.

2 Answers 2

1

If you want to import x and use it in another file, you just need to import it once. There's no need for another import or a "grab" function.

main.py:

from ImporterFile import x

print(x)

ImporterFile.py:

x = "hii!!"
Sign up to request clarification or add additional context in comments.

Comments

0

The regular import syntax doesn't support dynamic naming, but importlib does.

import importlib

import_name = "x"
imported_module = importlib.import_module("ImporterFile")

new_x = getattr(imported_module, imported_name)

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.