简体   繁体   中英

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.

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.

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:

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.

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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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