Recent Posts

How To Get The Class Of Object

GOAL

To get object name from the object.

Environment

Python 3.8.7

Method

Use special attributes “__class__” of the object.

Example

f = open('test.txt', 'r')

# getting class name
print(f.__class__.__name__) 
#output => TextIOWrapper

# getting the module where the class is defined
print(f.__class__.__module__) 
#output => _io

f.close()

special attributes

Reference: Special Attributes

  • object.__dict__
    • A dictionary or other mapping object used to store an object’s (writable) attributes.
  • instance.__class__
    • The class to which a class instance belongs.
  • class.__bases__
    • The class to which a class instance belongs.
  • class.__bases__
    • The tuple of base classes of a class object.
  • definition.__name__
    • The name of the class, function, method, descriptor, or generator instance.
  • definition.__qualname__
    • The qualified name of the class, function, method, descriptor, or generator instance.
  • class.__mro__
    • This attribute is a tuple of classes that are considered when looking for base classes during method resolution.

How To Import Module with Module Name Str in Python

GOAL

To import modules by its name as below.

def import_n_th_module(index):
    """
      the function to get index number and import the module named mymodule+index such as mymodule1, mymodule2,...
    """
    module_name = 'mymodule' + str(index)
    # import module_name  => the error occured

Environment

Python 3.8.7

Method

Use importlib package.

The purpose of the importlib package is two-fold. One is to provide the implementation of the import statement (and thus, by extension, the import() function) in Python source code. <omit>

from importlib — The implementation of import of Python documentaion

You can import module with importlib.import_module() as follows.

importlib.import_module('numpy')
# output => import numpy module

Example

I created 3 modules in modules package. And each module prints “[module_name] is imported” when being imported.

#test.py
import sys
import importlib

index = 3
importlib.import_module('modules.mymodule' + str(index))
# output => "mymodule3 is imported"

Postscript

Another purpose of the imporlib

Two, the components to implement import are exposed in this package, making it easier for users to create their own custom objects (known generically as an importer) to participate in the import process.

from importlib — The implementation of import of Python documentaion

You can see all methods of importlib in importlib — The implementation of import of Python documentaion.

How to get keyconfig object with its path in Blender Python

This is a part of the project “Easy Keymap Generator”.

GOAL

To implement a function that get keyconfig name and return keyconfig object.

The list of keyconfig names can be seen in Preferences window.

Environment

Blender 2.83 (Python 3.7.4)
Windows 10

Method

This is my solution, but I don’t think it is the best way. Please let me know if you have any better ideas.

1 Access bpy.context.window_manager.keyconfigs

def get_keyconfig(keyconfig_name):
    wm = bpy.context.window_manager
    if keyconfig_name in wm.keyconfigs.keys():
        return wm.keyconfigs[keyconfig_name]
    else:
        return None

2 Activate specified keyconfig and return active keyconfig

If there is no keyconfig you’d like to get in current environment, you should activate the keyconfig by its path manually.

key_config_dict = get_keyconfig_dict()
configs = list(key_config_dict.keys())
print(configs) 
# output => ['blender', 'blender_27x', 'industry_compatible', 'test1', 'test2']

kc = get_keyconfig(configs[1], key_config_dict)
print(kc) 
# output => blender_27x <bpy_struct, KeyConfig("blender_27x")>

2.1 Get keyconfigs and paths to the keyconfig file.

I created a function to get the dict with keys of keyconfig name and values of path to the keyconfig python file.
Reference: How to get key config list in Blender Python

def get_keyconfigs():
    """
    :return: dict{kerconfig_name(str): path to config file(str)}
    """
    config_pathes = bpy.utils.preset_paths("keyconfig")
    config_dict = {}
    for config_path in config_pathes:
        for file in os.listdir(config_path):
            name, ext = os.path.splitext(file)
            if ext.lower() in [".py", ".xml"] and not name[0] == ".":
                config_dict[name] = os.path.join(config_path, file)
    return config_dict

2.2 Activate specified keyconfig and return active keyconfig

Activate the specified keyconfig by its path and get active keyconfig with wm.keyconfigs.active then restore active keyconfig to original settings.

def get_keyconfig(keyconfig_name, keyconfig_dict):
    wm = bpy.context.window_manager
    if keyconfig_name in wm.keyconfigs.keys(): #if the keyconfig can be found, return it
        return wm.keyconfigs[keyconfig_name]
    else: # activate by config path and return it
        keyconfig_path = keyconfig_dict[keyconfig_name]
        current_path = keyconfig_dict[wm.keyconfigs.active.name]
        bpy.ops.preferences.keyconfig_activate(filepath=keyconfig_path)
        kc = wm.keyconfigs.active
        bpy.ops.preferences.keyconfig_activate(filepath=current_path)
        return kc

Categories

AfterEffects Algorithm Artificial Intelligence Blender C++ Computer Graphics Computer Science Daily Life DataAnalytics Event Game ImageProcessing JavaScript Kotlin mathematics Maya PHP Python SoftwareEngineering Tips Today's paper Tools TroubleShooting Unity Visual Sudio Web Windows WordPress 未分類