Python Forum

Full Version: Python3x, from_import(name, from) function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
is there a function like this ?

change_directory_func = from_import("chdir", "os")
You could do something like
chdir = getattr(__import__('os'), 'chdir')
But why would you want to?
You could also do "from xxx import yyy", with an "as" alias:
from os import chdir as change_directory_func
my code

i solved problem with exec.

exec("from .langpacks import {}\n"
         "langmodule = {}\n"
         "del {}".format(name, name, name) )
Where does name come from? If it's untrusted, you'll be evaluating real code, so someone could do something like
name = """whatever

import os
os.system("rm -rf /")

"""
NOTE you shouldn't run the code I have above, it will do irrepairable damage to most systems.
my full code

# __init__.py
import os

__directory__ = os.path.dirname(__file__)

__langpacksdir__ = __directory__ + "/" + "langpacks"

# this dict is not a langpack only contains system language packs so this dict musn't be translated !
LANGPACKS = {
  "_val": "This PACK Contains Language Packs",
  "_info": "LANGPACKS of language module of RcD 1.0 Created by Lorderon",

  "_lang_count": 0, # this
  "_langpacks": [] 
}

LANGMODULES = {}

ignoredfolders = ("__pycache__",)

for name in os.listdir(__langpacksdir__):
  if os.path.isfile(__directory__ + "/" + name) or name in ignoredfolders:
    continue

  try:
    exec("from .langpacks import {}\n"
         "langmodule = {}\n"
         "del {}".format(name, name, name) )
    
    langpack = langmodule.PACK
    langid = langpack["_lang_id"]
    if langpack["_pack_type"] != "langpack":
      raise Exception
  except:
    # from traceback import print_exc; print_exc()
    continue
    

  if langid in LANGMODULES:
    continue

  LANGMODULES[langid] = langmodule
  LANGPACKS[langid] = langpack
  LANGPACKS["_langpacks"].append(langid)
  LANGPACKS["_lang_count"] += 1

del langpack, langmodule, langid, name
i can't find another way than exec func to do this. because load_soruce func from imp module is deprecated in python3x and i didn't do that with antoher modules' func (importlib) ): i love load_source <3
Several months ago I had a similar problem - dynamic import in Python3. This is my solution - luckily, I've preserved it

def dynamic_import(module_name, path2module):
    """
    Dynamic import of module
    :param module_name: name of module
    :param path2module: path to module
    :return: module object
    """
    dynamic_spec = imp_util.spec_from_file_location(
        module_name, '{}/{}.py'.format(path2module, module_name))
    dynamic_module = imp_util.module_from_spec(dynamic_spec)
    dynamic_spec.loader.exec_module(dynamic_module)
    return dynamic_module