Travis Griggs
Travis Griggs

Reputation: 22252

Python import scope issue

I'm trying to do some script reuse for some python build scripts. An abbreviated version of my "reusable" part looks like (_build.py):

Sources = []
Sources += glob('*.c')
Sources += glob('../FreeRTOS/*.c')
...
def addSources(directory, *rest):
  for each in rest:
    Sources += ['../'+directory+'/'+each+'.c']

def addSharedSources(*args):
  addSources('Shared', *args)

Then in the customized part, I have something like (build.py):

#!/usr/bin/env python
from _build import *
...
#Additional source files from ../Shared, FreeRTOS and *.c are already in
addSharedSources('ccpwrite', 'discovery', 'radioToo', 'telemetry', 'utility')

Unfortunately, when I try to run build.py, I get a traceback that looks like:

Traceback (most recent call last):
File "./build.py", line 8, in <module>
 addSharedSources('ccpwrite', 'discovery', 'radioToo', 'telemetry', 'utility')
File "/Users/travisg/Projects/treetoo/Twig/_build.py", line 49, in addSharedSources
 addSources('Shared', *args)
File "/Users/travisg/Projects/treetoo/Twig/_build.py", line 46, in addSources
 Sources += ['../'+directory+'/'+each+'.c']
UnboundLocalError: local variable 'Sources' referenced before assignment

So even though I did the wildcard import, it would appear that when the import function is called, it's not referencing my "global" variable imported from the original. Is there a way to make it work? I toyed around with global, but that didn't seem to do what I wanted.

Upvotes: 1

Views: 151

Answers (1)

alexis
alexis

Reputation: 50200

This has nothing to do with the import. You'll have the same problem if you run _build.py directly. The problem is that the function addSources is modifying the global Sources without declaring it global. Insert a global declaration in the addSources function, and all should be well.

Explanation: It is very easy to write this kind of code by mistake. So python allows you to read a global variable without declaring it global, but not to modify it.

Upvotes: 2

Related Questions