UnboundLocalError: local variable referenced before assignment

ch1zra ch1zra at gmail.com
Tue Jun 8 05:28:22 EDT 2010


On Jun 8, 10:59 am, Bryan <bryanjugglercryptograp... at yahoo.com> wrote:
> ch1zra wrote:
> > I have following code :
>
> > import os, time, re, pyodbc, Image, sys
> > from datetime import datetime, date, time
> > from reportlab.lib.pagesizes import A4
> > from reportlab.lib.units import cm
> > from reportlab.pdfgen import canvas
> > from reportlab.pdfbase import pdfmetrics
> > from reportlab.pdfbase.ttfonts import TTFont
> > import mkTable
>
> > mkTable.mkTable()
>
> > and then file mkTable.py located in same directory has :
>
> > def mkTable():
> >     global canvas
> >     canvas = canvas.Canvas(fname, pagesize=A4)
> >     ... and so on
>
> > this gives me following traceback:
>
> > Traceback (most recent call last):
> >   File "C:\py\pdf_test.py", line 36, in <module>
> >     mkTable.mkTable()
> >   File "C:\py\mkTable.py", line 38, in mkTable
> >     canvas = canvas.Canvas("K_lista.pdf", pagesize=A4)
> > UnboundLocalError: local variable 'canvas' referenced before
> > assignment
>
> Python doesn't have one global namespace. Each module (file) has its
> own namespace, which is a Python dict, and 'global' means defined in
> the containing module's dict. Put the import:
>
>   from reportlab.pdfgen import canvas
>
> in the mkTable.py file. That brings 'canvas' into the mkTable module's
> namespace.
>
> Python programs commonly import the same module multiple times. Only
> the first import runs the body of the imported module. Subsequent
> imports merely bring the names into the importing module's namespace.
>
> --
> --Bryan Olson

thanx so much, it worked.
I am getting some other problems now, but will use this logic to fix
it.
thanx once again :)



More information about the Python-list mailing list