Python Forum
How to assign a module to a variable even if it's not defined?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to assign a module to a variable even if it's not defined?
#1
Hello, I want to import modules from files, I need to store them into variables and I need their names as strings because I must check if the modules python files exist or not for example.
My question is, how to assign a module to a variable even if it's not defined? See the line 1 below, thanks.

module = math # NameError: name 'math' is not defined
module_str = module.__name__ # It should be 'math', but not 'module' because it's not a variable name.
import module
To make everything clear, here is another example, I want to store the string 'math' into a variable, then I import it:
import 'math' # SyntaxError: invalid syntax
Reply
#2
This looks very much like XY problem. Would you elaborate on what the ultimate goal is? "check if the modules python files exist or not" is not very clear.

e.g. if you want to check that trying to import module will not raise error - there is idiomatic way to do it using try/except

if you want to import module by using name string - look at importlib
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
New question: "How to create a module or variable with the name from a string?"
import sys
import os
import importlib

dir = os.path.dirname(bpy.data.filepath)
dir = os.path.join(dir, "Scripts") # The script must be located in that folder
if not dir in sys.path:
    sys.path.append(dir)
'''
#---------- Method 1 ----------
# There is no problem if there is no 'for', but I will have many modules, so I can't do these.
main = importlib.import_module('main')
MyModule = importlib.import_module('MyModule')'''

#---------- Method 2 ----------
module_names = (
    'main',
    'MyModule')

for name in module_names:
    value = importlib.import_module(name)
    create_var_by_str(name, value) # FIXME: Here is my problem, I want to create a variable named of the
                                   # value of 'name', and assign to it the value of 'value'.
Reply
#4
again, why are you doing all this?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
I'm sorry.
The terms say that I come back if I find the solution. I use 'exec' to create a variable from string.

>>> exec("abc = 123")
>>> abc
123

Bye, I will make effort next time, I will try to be perfect.
Reply
#6
(Aug-12-2020, 03:16 PM)mandaxyz Wrote: The terms say that I come back if I find the solution. I use 'exec' to create a variable from string.
Yes,but a better way could be to use a data structure like dictionary.
What's really happens when do exec("abc=123") or just abc = 123,is that Python map this to a internal global dictionary.
>>> exec("abc = 123")
>>> globals()['abc']
123
>>> type(globals())
<class 'dict'>
So the way to make this more clear is to use real visible dictionary.
>>> d = dict(abc=123, foo=456)
>>> d
{'abc': 123, 'foo': 456}
>>> d['abc']
123

# Then also get method like get
>>> d.get('abc', 'Not in record')
123
>>> d.get('abcd', 'Not in record')
'Not in record'
>>> d.get('foo', 'Not in record')
456
mandaxyz Wrote:Bye, I will make effort next time, I will try to be perfect
To be perfect is a goal we all will fail at Wink
I think just a little expatiation of the goal of doing this was the point here.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error when refering to class defined in 'main' in an imported module HeRo 2 584 Apr-13-2021, 07:22 PM
Last Post: HeRo
  When I print a key from dict it prints it but when I try to assign it to a variable I stefanvelikov 3 628 Nov-27-2020, 01:29 PM
Last Post: stefanvelikov
  Function will not return variable that I think is defined Oldman45 6 1,253 Aug-18-2020, 08:50 PM
Last Post: deanhystad
  Variable not defined Heyjoe 4 905 Jul-10-2020, 11:27 PM
Last Post: Heyjoe
  python library not defined in user defined function johnEmScott 2 921 May-30-2020, 04:14 AM
Last Post: DT2000
  Error: variable can not be defined julio2000 2 1,401 Feb-09-2020, 08:51 PM
Last Post: julio2000
  using module variable jacklee26 4 919 Nov-13-2019, 01:36 AM
Last Post: jacklee26
  How I can use multiprocessing with upickled module variable? AlekseyPython 3 1,880 Oct-31-2019, 06:09 AM
Last Post: AlekseyPython
  How to assign this output to a string variable? Pedroski55 3 1,200 Apr-18-2019, 07:23 AM
Last Post: Yoriz
  Variable defined but python wont recognize it. FWendeburg 3 1,642 Feb-19-2019, 10:43 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020