Deep Import Tutorial

Abstract

This allows you to retrieve an attribute defined by a string. In particular you can subclass an object based off of a game property.

Prerequisites

str.rpartition
importlib.import_module

Code

def deepImport(path):
  """
  allows you to dynamically import an attribute from a module using a string
  path = string indicating where to import from
  return = the module attribute imported
 
  eg:
  ClassDef = deepImport('some.deep.classDef.ClassDef')
  newObj = ClassDef()
  """
 
  # https://docs.python.org/3/library/importlib.html#importlib.import_module
  from importlib import import_module
 
  mod, dnu, attr = path.rpartition('.')
 
  # First we import the module.
  mod = import_module(mod)
 
  # Then we get the attrabute from that module.
  return getattr(mod, attr)

Questions

Edit this post to ask or answer questions.

Further Reading

Subclass GameObject

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License