简体   繁体   English

将 function 的文档字符串传递给另一个文件 python3

[英]Passing docstring of a function to another file python3

I'm using apispec in order to generate openapi specification (swagger) to be used for further utilization in AWS.我正在使用 apispec 来生成 openapi 规范(swagger),以便在 AWS 中进一步使用。

I was trying to optimize my current file by creating another file that contains functions with docstrings related to the routes implemented.我试图通过创建另一个包含与实现的路由相关的文档字符串的函数的文件来优化我当前的文件。 I'm still not sure if it is possible or not but what I'm sure about is that it didn't worked for me.我仍然不确定这是否可能,但我确定它对我不起作用。 Here's what I've implemented so far:到目前为止,这是我已经实现的:

The function below login_doc() inside the file login_file.py contains the docstring related to the login route.文件login_file.pylogin_doc()下面的 function 包含与登录路由相关的文档字符串。

def login_doc():
"""
post:
  responses:
    "200":
      description: "200 response"
      content:
        application/json:
          schema:
          $ref: "#/components/schemas/Empty"
"""
pass

And in the file generate_openapi.py I did this:在文件generate_openapi.py我这样做了:

import login_file

@app.route('/login', methods=['POST'])
def login():
  login_file.login_doc.__doc__

PS: the rest of the imports are working just fine, just removed them when posting this question. PS:进口的 rest 工作得很好,只是在发布这个问题时删除了它们。

Unfortunately, this does not work for me.不幸的是,这对我不起作用。 As I said before, I'm trying to minimize the lines of code of generate_openapi.py so that it can be more readable and comprehensible.正如我之前所说,我试图尽量减少generate_openapi.py的代码行数,使其更具可读性和可理解性。 Thank you all in advance for your time.提前感谢大家的时间。

While I doubt that it aids readability, if you define the docstring outside the function, you can set the docstring after defining the function, like so:虽然我怀疑它是否有助于可读性,但如果您在 function 之外定义文档字符串,则可以在定义 function 之后设置文档字符串,如下所示:

import login_file

@app.route('/login', methods=['POST'])
def login():
  ...

login.__doc__ = login_file.login_doc.__doc__

Alternatively, define a decorator to change the docstring of your function.或者,定义一个装饰器来更改 function 的文档字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM