如何在python中全局导入?

时间:2018-08-14 10:47:19

标签: python

当我偶然发现某些东西时,我才刚开始使用reportlab。我从一些基本代码开始:

MySubClass

这给了我以下错误:

user_0001
user_0002
user_0003
user_0004
user_0005

我已经知道,像其他语言一样,不允许在python中自由使用全局变量,并且this post要求使用from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas def generateDoc(docName, title, codefilesFolderPath, docTextFilePath): canvas = canvas.Canvas(docName, pagesize=letter) canvas.setLineWidth(.3) canvas.setFont('Helvetica', 12) canvas.drawString(30,750,'OFFICIAL COMMUNIQUE') canvas.save() generateDoc("temp.pdf","","","") 关键字。但是我无法在上面的代码中得到应该怎么做。

我曾尝试将UnboundLocalError: local variable 'canvas' referenced before assignment 放在各个地方,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您的局部变量canvas隐藏了导入的模块canvas

您可以直接导入Canvas

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas

def generateDoc(docName, title, codefilesFolderPath, docTextFilePath):

    canvas = Canvas(docName, pagesize=letter) 
    canvas.setLineWidth(.3)
    canvas.setFont('Helvetica', 12)
    canvas.drawString(30,750,'OFFICIAL COMMUNIQUE')
    canvas.save()

generateDoc("temp.pdf","","","")