Tushaar
Tushaar

Reputation: 307

Extract python file name from a class type object in Python

I have the below directory structure in my python project.

checks/
  __init__.py
  check_1.py
  check_2.py
main.py

Contents inside init.py file are as below where Check1 and Check2 are classes inside check_1.py and check_2.py respectively -

__init__.py - 

from .check_1 import Check1
from .check_2 import Check2

Inside main.py, i am creating the below dictionary -

import checks
check_dict={obj:name for name, obj in vars(checks).items() if isinstance(obj, type)}

Current Output -

{<class 'checks.check_1.Check1'>: 'Check1', <class 'checks.check_2.Check2'>: 'Check2'}

Expect Output -

{check_1: 'Check1',check_2: 'Check2'}

Upvotes: 0

Views: 292

Answers (1)

RJ Adriaansen
RJ Adriaansen

Reputation: 9619

__module__ will get you the name of the module, eg. checks.check_1. If you only need check_1 you can split the string:

check_dict={obj.__module__.split('.')[1]:name for name, obj in vars(checks).items() if isinstance(obj, type)}

Upvotes: 1

Related Questions