python rtype docstring/restructured text for class factories/selectors

末鹿安然 提交于 2019-12-06 19:50:29

问题


:rtype: specifies that this is type of returned object

Therefore, when I create object obj in following snippet I receive warning from IDE, that cls is not callable, since IDE expects, that cls is object of type SomeAbstractClass, and I want SomeAbstractClass itself

IDE is right, since this is default behaviour. But how can I specify, that I am returning class, not instance of class?
Specifying type instead of SomeAbstractClass helps a bit, but not a solution, since no further introspection available.

def class_selector(data):
    """
    :rtype: SomeAbstractClass
    :return: Return some class based on given parameters
    """

    return get_from.get(data.name)
cls = class_selector(data)
obj = cls(data.more_data)

Meanwhile i solve this by adding """:type: SomeAbstractClass""" after object creating, but this does not cancel the warning and it's dirty solution.

Btw, talking about python 2.x


回答1:


if the data is an instance of SomeAbstractClass, you can use the following snippets:

example 1:

def class_selector(data):
    """
    return: Return the class of data
    """

    return type(data)

example 2:

def class_selector(data):
    """
    return: Return the class of data.
    """

    return data.__class__

And if you want use data.name to specify a class, you can use this:

def class_selector(data):
   """
   return: Return a class specified by data.name
   """
   return type(globals()[data.name])  #or use globals()[data.name].__class__

and you should catch the KeyError exception when you use this



来源:https://stackoverflow.com/questions/22593560/python-rtype-docstring-restructured-text-for-class-factories-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!