如何在Python中将包含路径的字符串转换并使用该字符串访问类?

huangapple go评论88阅读模式
英文:

How to convert a string containing a path and access the class using that string in Python?

问题

我想要处理一个格式为"package.file.module.classname"的字符串,并使用它来访问特定类或函数的文档字符串。

我可以导入初始包,但路径的其余部分可以根据任何输入而灵活变化。

我尝试过使用getattr(sys.modules[__name__], classname),但似乎只限于当前包内部,无法扩展到外部。

英文:

I'm looking to take in a string of the format "package.file.module.classname" and use that to access the docstring of the particular class or functions within.

I can import the initial package, but the remaining part of the path remains flexible to any input.

I've attempted using getattr(sys.modules[__name__], classname) but that seems to be limited to within a current package and cannot be extended outside it

答案1

得分: 0

导入模块动态地

module = __import__(module_name)

然后动态实例化类

my_class = getattr(module, class_name)
英文:

Import the module dynamically

module = __import__(module_name)

Then instantiate the class dynamically

my_class = getattr(module, class_name)

答案2

得分: 0

在将字符串解析为模块和类名称后,我认为您需要使用 importlib 导入模块,然后使用 getattr 按名称从模块获取类对象。

之后,我能够使用 inspect 获取文档字符串。

这里有一个示例:假设您有一个名为 birds 的鸟类模块:animals/birds.py

class Duck:
    """
    A duck class
    """
    def __init__(self, name):
        self._name = name

    def quack(self):
        """
        A quack method
        """
        print(f"{self._name} is quacking")

此代码将返回一个以类和方法名称为键,其文档字符串为值的 dict

import importlib
import inspect


def get_docstrings(class_string):
    try:
        # 将字符串分割为模块和类名称部分
        path_parts = class_string.split('.')
        module_name = '.'.join(path_parts[:-1])
        class_name = path_parts[-1]
        module = importlib.import_module(module_name)

        # 从模块中获取类对象
        class_obj = getattr(module, class_name)

        doc_strings = {}

        # 返回类的文档字符串
        doc_strings[class_name] = class_obj.__doc__

        for name, member in inspect.getmembers(class_obj):
            if inspect.isfunction(member):
                doc_strings[name] = member.__doc__

        return doc_strings

    except (AttributeError, ImportError, IndexError):
        return None

# 示例用法
docstring = get_docstrings("animals.birds.Duck")

请注意,文档字符串将包含换行转义符和其他格式:

{
  'Duck': '\n    A duck class\n    ',
  '__init__': None,
  'quack': '\n        A quack method\n        '
}
英文:

After parsing the string into module and class names, I think you need to use importlib to import the module, then use getattr to get the class object from the module by name.

After that, I was able to get docstrings using inspect

Here's an example: Say you have a birds module: animals/birds.py:

class Duck:
    """
    A duck class
    """
    def __init__(self, name):
        self._name = name

    def quack(self):
        """
        A quack method
        """
        print(f"{self._name} is quacking")

This code will return a dict with class and method names as keys, and their docstrings as values:

import importlib
import inspect


def get_docstrings(class_string):
    try:
        # Split the string into module, class name parts
        path_parts = class_string.split('.')
        module_name = '.'.join(path_parts[:-1])
        class_name = path_parts[-1]
        module = importlib.import_module(module_name)

        # Retrieve the class object from the module
        class_obj = getattr(module, class_name)

        doc_strings = {}

        # Return the docstring of the class
        doc_strings[class_name] = class_obj.__doc__

        for name, member in inspect.getmembers(class_obj):
            if inspect.isfunction(member):
                doc_strings[name] = member.__doc__

        return doc_strings

    except (AttributeError, ImportError, IndexError):
        return None

# Example usage
docstring = get_docstrings("animals.birds.Duck")

Note that docstrings will have new line escapes and other formatting:

{
  'Duck': '\n    A duck class\n    ',
  '__init__': None,
  'quack': '\n        A quack method\n        '
}

huangapple
  • 本文由 发表于 2023年6月9日 02:44:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定