[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Declaring variables in function as if at code's line-level



Hi,

To answer Nick's, question: yes. Anything in a module's global namespace is directly visible from a function declared within the module, unless hidden by a function argument or local variable having the same name. Even then, you can use the globals function to access the global names.

And yes Lee, you have it right. The Python compiler would notice the assignment to font with function something and therefore create a function local variable that hides the global font variable. Of course, the global font can still be accessed directly through the module's global dictionary:

from game import font

def something():
      font = 1
globals()['font'].render("or other") # call imported global font function
      print font  # print local font value: "1"

On 10/03/12 09:45 PM, Lee Buckingham wrote:
I believe so.  Just don't say something like:

def something():
      font = 1

...not that you would, but if for whatever reason it happened, you
would have created a fuction variable called 'font'  and the global
namespace would be ignored because of it.

(Do I have this right, guys?)


-Lee-



On Sat, Mar 10, 2012 at 9:34 PM, Nick Arnoeyts<nickarnoeyts@xxxxxxxxx>  wrote:
I have a little additional question about the explanation Lee gave.

Is it possible to use class instances from the global namespace in a
function? For example:

from game import screen, font

def get_text(string):
     font.render(string) # parts cut out because I'm in a hurry

I figure this is probably possible, but it can't hurt to ask for future
reference.