你如何注释自定义类?

时间:2016-05-13 16:18:04

标签: python python-3.x annotations pycharm

假设我有一个班级Shard,我的方法返回值应该是listShard个对象。

my_method(args) -> ??:

当我从List导入typing并指定List[Shard]时,Pycharm启动了一个错误(错误与它无法找到碎片有关)。

以下是有问题的方法:

def _return_shards(self, sql: str = None) -> List[Shard]:
        """
        Queries the database to return a sequence of all the database clusters
        and shards, and then creates Shard objects with the information.

        @type conn_info: dict
        :param conn_info: Database information containing the host, port, user,
         database, and password.
         @type sql: str

        :return: A list of Shard items
        """
        logging.info('Creating shards.')
        cursor = self._return_cursor(self.canvas_conn)

        stock_query = '''
              SELECT
                database_server_id || 'dr' database_server_id
              , CASE
                  WHEN database_server_id LIKE 'cluster1' AND name IS NULL THEN 'canvas'
                  WHEN database_server_id LIKE 'cluster4' AND name IS NULL THEN 'canvas'
                  WHEN name IS NULL THEN database_server_id
                  ELSE name
                END AS database_name
                ,SUBSTRING(database_server_id FROM '\d+$')::INT cluster_id
                ,CASE
                  WHEN name IS NULL THEN SUBSTRING(database_server_id FROM '\d+$')::INT
                  ELSE SUBSTRING(name FROM '\d+$')::INT
                END AS shard_id
              FROM canvas.switchman_shards
              WHERE database_server_id LIKE 'cluster%'
              ORDER BY cluster_id, shard_id
              '''
        if sql:
            cursor.execute(sql)
        else:
            cursor.execute(stock_query)
        results = cursor.fetchall()
        self._set_reporter_total_shards(count=len(results))
        return [Shard(
            *result,
            job=self.job,
            manifest=self.manifest,
            reporter=self.reporter.create_slave(db=result[0], schema=result[1])
        ) for result in results]

即使NameError: name 'Shard' is not defined类在同一模块中定义,错误仍为Shard

1 个答案:

答案 0 :(得分:1)

Shard尚未定义,因为您仍处于类定义的中间,或者因为Shard定义在此类下方。 Give the name as a string

def _return_shards(self, sql: str = None) -> List['Shard']: