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?
#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


Messages In This Thread
RE: How to assign a module to a variable even if it's not defined? - by mandaxyz - Aug-12-2020, 02:48 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Variable not defined even though it is CoderMerv 3 1,810 Mar-28-2024, 02:13 PM
Last Post: Larz60+
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 1,572 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 7,264 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  [variable] is not defined error arises despite variable being defined TheTypicalDoge 4 3,571 Apr-05-2022, 04:55 AM
Last Post: deanhystad
  Error when refering to class defined in 'main' in an imported module HeRo 2 3,233 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 3,150 Nov-27-2020, 01:29 PM
Last Post: stefanvelikov
  Function will not return variable that I think is defined Oldman45 6 4,737 Aug-18-2020, 08:50 PM
Last Post: deanhystad
  Variable not defined Heyjoe 4 3,507 Jul-10-2020, 11:27 PM
Last Post: Heyjoe
  python library not defined in user defined function johnEmScott 2 5,003 May-30-2020, 04:14 AM
Last Post: DT2000
  Error: variable can not be defined julio2000 2 3,944 Feb-09-2020, 08:51 PM
Last Post: julio2000

Forum Jump:

User Panel Messages

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