problem with variable and function

Chris Rebert clp2 at rebertia.com
Sun Mar 14 20:24:11 CET 2010


> On 3/14/10, Chris Rebert <clp2 at rebertia.com> wrote:
>> On Sun, Mar 14, 2010 at 10:26 AM, Alex Hall <mehgcap at gmail.com> wrote:
>>> Hi all,
>>> I have a file with a dictionary and a function. The dictionary holds
>>> the name of the function, and the function references the dictionary.
>>> If I put the dictionary first, the function is happy but the
>>> dictionary says the function is not defined. If I switch the two and
>>> put the function first, the function says the dictionary does not
>>> exist. Does anyone have an idea as to how I can make both of them
>>> happy?
>> <snip>
>>> Reverse it, though:
>>>
>>> def myFunc():
>>>  myOtherVar=myVar
>>>
>>> myVar={
>>>  1:myFunc
>>> }
>>>
>>> and the function myFunc does not see the dictionary.
>>
>> Please be more specific in what you mean by it not "seeing" the
>> dictionary, because the "reversed" approach *should* work:
>>
>> $ python
>> Python 2.6.4 (r264:75706, Feb 25 2010, 01:21:39)
>> [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> def foo():
>> ...     bar = baz
>> ...     print bar
>> ...
>>>>> baz = {1:foo}
>>>>> foo()
>> {1: <function foo at 0x37b870>}

On Sun, Mar 14, 2010 at 11:12 AM, Alex Hall <mehgcap at gmail.com> wrote:
> Below is pasted the function which is looking for the "funcs"
> dictionary, as well as the dictionary. They appear in my py file in
> this order, yet I get an error in nextMode() that "global name 'funcs'
> is not defined". Oddly, the keys dictionary works fine; it is defined
> above the nextMode function.

Please include the full exception Traceback.
Also, please don't top-post in the future.

> def nextMode():
>  global HOTKEYS
>  global HOTKEY_ACTIONS
>  global mode

You don't need a `global` declaration unless your function needs to
rebind the global variable in question.
So you can remove the next 4 global declarations; they're unnecessary.

>  global modes
>  global modeNum
>  global modeNames
>  global funcs
>  #mode=mode+1
>  #check to make sure the newly selected mode is enabled
>  tmp=0
>  while(tmp<modeNum):
>  mode=(mode+1)%modeNum
>  if(sys.modules[modeNames[mode]].enabled=='True'):
>   break #break on the first enabled mode we find
>  #end if
>  tmp+=1
>  #end while
>  HOTKEYS=keys[mode]
>  HOTKEY_ACTIONS=funcs[mode]
>  registerHotkeys()
>  speak("Now in "+str(modes[mode])+" mode.")
> #end def
>
> #we now have the default mode to be used, but what if it is disabled?
> if(sys.modules[modeNames[mode]].enabled=='False'):
>  nextMode()

How is this call supposed to work when `funcs` (which nextMode() uses)
hasn't been defined yet?!

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list