Category: Tips

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 preset paths in Blender Python

This is a tips for blender addon developers.

GOAL

To get the list of paths to preset directories, blender system preset and user preset and so on.

These are examples of the preset directory.

  • presets of interface theme
    • C:\Program Files\Blender Foundation\Blender 2.83\2.83\scripts\presets\interface_theme
    • C:\Program Files\Blender Foundation\Blender 2.83\2.83\scripts\addons\presets\interface_theme’
  • presets of keyconfig
    • C:\Program Files\Blender Foundation\Blender 2.83\2.83\scripts\presets\keyconfig
    • C:\Users\<USER_NAME>\AppData\Roaming\Blender Foundation\Blender\2.83\scripts\presets\keyconfig

Environment

Blender 2.83 (Python 3.7.4)
Windows 10

Method

Use bpy.utils.preset_paths(subdir) that returns the list of paths to the preset directory of subdir.

(more…)

How to fit the widget to the parent layout in PySide2

GOAL

To fit the sizes of the children widgets to the layout of the parent. In other words, to remove the space around widgets from the layout.

Environment

Windows 10
Python 3.8.7
PySide2 5.15.2

Method

There are 2 steps to delete margin space from the layout.

  1. Set the margin of the layout 0
  2. Set the spacing of the layout 0
(more…)

How to fit the selected color to the cell in QTreeWidget

The length of selected color depends on the length of the string in QTreeWidget of PySide2. How can I fit the length of the cell?

GOAL

To fill the color to fit the size of the cell when the item is selected. (See the article “How to select one column of QTreeWidgetItem in PySide2” to generate an tree widget that allows users to select each item.)

Environment

Windows 10
Python 3.8.7
PySide2 5.15.2

Method

Set show-decoration-selected of qss(QStyleSheet) that can be used for QTreeWidget, QTreeView, QListWidget and QListView.

Controls whether selections in a QListView cover the entire row or just the extent of the text.

from Qt Style Sheets Reference

Use setStyleSheet to set qss to the widget as below.

self.tree_widget.setStyleSheet('QTreeView { show-decoration-selected: 1;}')

See the official documentation “Qt Style Sheets” for details about qss.

[Tips]How to access each n-th item of lists

Though the following is one of the ways to access items of multiple list, an error “index out of range” will occur when the lengths of the lists are different. How can I solve it?

list1 = ["A", "B", "C", "D"]
list2 = [1, 2, 3, 4]
list3 = ["Apple", "Orange", "Banana", "Peach"]

for i in range(len(list1)):
    print(list1[i], list2[i], list3[i])

The output is as below.

A 1 Apple
B 2 Orange
C 3 Banana
D 4 Peach

GOAL

To access each n-th item of multiple lists in one for loop.

(more…)

How to see revision and restore previous article in WordPress

I mistakenly overwrote my article in WordPress. How can I recover them?

GOAL

To see revisions of the article and recover previous version in WordPress.

Environment

WordPress 5.6
Windows 10

Methods

Open the post and click “Revisions” in right sidebar.

Select the revision you’d like to recover and click “Restore This Revision” button.

What to do if “Restore This Revision” button is disable

“Restore This Revision” button couldn’t be pressed for some reasons.

You can copy the elements of previous version and paste it into the editor.

How To Get Attributes Of Object In Python

This is just a tips.

GOAL

To get the list of attributes of an object in Python

Environment

Python 3.7.4

Method

Use built-in function dir([object]) method as below.

dict1 = {"a":1, "b":2}
print(dir(dict1))
# output => ['__class__', '__contains__', '__delattr__', ... , 'setdefault', 'update', 'values']

dir() can takes not only variable but also any objects such as ‘type’ itself.

print(dir(dict))
# output is the same as print(dir(dict1)) above 

dir() can be used for user-defined class, too.

class User:
    number = 0
    def __init__(self, name, age=0):
        self.name = name
        self.age = 0
        self.addNum()
    def profile(self):
        print("Name:"+self.name, " Age:"+self.age)
    @classmethod
    def addNum(cls):
        cls.number += 1g

user1 = User("John", 20)
print(dir(user1))
# output => ['__class__', '__delattr__', '__dict__', ... , 'addNum', 'age', 'name', 'number', 'profile']

dir([object]) function return the list of only the object’s attributes. So the list returned by dir(User) includes class variables “number” but don’t include instance variables “name” and “age”.

 class User:
    number = 0
    def __init__(self, name, age=0):
        self.name = name
        self.age = age
        self.addNum()
    def isAdult(self):
        if 18 <= self.age:
            return True
        else:
            return False
    def profile(self):
        print("Name:"+self.name, " Age:"+self.age)
    @classmethod
    def addNum(cls):
        cls.number += 1

print(dir(User))
# output => ['__class__', '__delattr__', '__dict__', ... , 'addNum', 'number', 'profile']

If dir() takes no argument, it returns the list of names in the current local scope.

user1 = User("John", 20)
num1 = 10
dict1 = {"a":1, "b":2}
print(dir())
# output => ['User', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'dict1', 'num1', 'user1']

Appendix

Module “inspect” is also used for getting information of objects as below.

import inspect
user1 = User("John", 20)
print(inspect.getmembers(user1))
# getmembers returns the pairs of (attribute, its value)
# output => [('__class__', <class '__main__.User'>), ('__delattr__', <method-wrapper '__delattr__' of User object at 0x000002B8A1BBAEB0>), ('__dict__', {'name': 'John', 'age': 20}), ... , ('name', 'John'), ('number', 1), ('profile', <bound method User.profile of <__main__.User object at 0x000002B8A1BBAEB0>>)]

Function vars([object]) only return __dict__ attributes of the object that is the dict of (variables, value).

user1 = User("John", 20)
print(vars(user1))
# output => {'name': 'John', 'age': 20}

What is “Color” in Object Properties in Blender

GOAL

To understand how to use object color.

Environment

Blender 2.83
Windows 10

What is Object Properties?

The Properties shows and allows editing of many active data, including the active scene and object.

from Properties page in Blender2.91 Manual

You can change the attributes of the object from “Object Properties” tab. The color can be set in the “Visibility” menu.

How to display the object color

1. Change the object color

2. Change the renderer into “Workbench”

The Workbench Engine is a render engine optimized for fast rendering during modeling and animation preview.

from Introduction of workbench in Blender2.91 Manual

3. Set the color “Object”

You can select colors that the Workbench uses to render objects from single, Object, Material, Random, Vertex and Texture. See “Color” page of workbench in Blender2.91 Manual for details.

4. Rendering

Change the viewport shading “rendered”.

Rendered result

“python script failed check the message in the system console” in Blender

This is for beginners.

Error Detail

When I ran python script below in blender, the error message “python script failed check the message in the system console” is displayed.

import bpy.data
print(bpy.data.objects)
from Blender

Solution

Open the system console and check the message but where is the system console?

How to open the system console

Click Window > Toggle System Console

You can see the message on the generated window.

How to set keymap in Blender

GOAL

To add some functions into keymap in Blender. I added “Toggle Quad View” into the “Industry Compatible” keymap.

There is no shortcut key of “Toggle Quad View” in Industry Compatible keymap in contrast to Blender keymap.

Environment

Blender 2.83
Windows 10

Method

Open and right-click the menu to which you’d like to add shortcut key.

Click “Assign Shortcut” and press the key to assign.

Press the key and the shortcut key is registered.