Global dictionary or class variables


in an application I have to use some variables with fixed valuse. For example, I'm working with musical notes, so I have a global dictionary like this: natural_notes = {'C': 0, 'D': 2, 'E': 4 ....} This actually works ...
Posted On: Saturday 24th of November 2012 01:09:41 AM Total Views:  49
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




global variables

Does anyone know how the variables label and scale are recognized without a global statement or parameter, in the function resize() in this code: #!/usr/bin/env python from Tkinter import * def resize(ev=None): label.config(font='Helvetica -%d bold' % \ scale.get()) top = Tk() top.geometry('250x150') label = Label(top, text=' World!', font='Helvetica -12 bold') label.pack(fill=Y, expand=1) scale = Scale(top, from_=10, to=40, orient=HORIZONTAL, command=resize) scale.set(12) scale.pack(fill=X, expand=1) quit = Button(top, text='QUIT', command=top.quit, activeforeground='white', activebackground='red') quit.pack() mainloop()
VIEWS ON THIS POST

101

Posted on:

Monday 5th November 2012
View Replies!

Re: Imported globals?

Valentina Vaneeva wrote: > > > I'm new to Python and I've found something in its interpreter that I > don't quite understand, and I don't really know how to correctly > formulate a search query. Here's the question. > > If we have a file module_a.py with the following content: > > | #!/usr/bin/env python > | > | value = 'initial' > | > | def change_value(): > | global value > | value = 'changed' > > and a file module_b.py: > > | #!/usr/bin/env python > | > | from module_a import value, change_value > | > | change_value() > | print value > > Then, if we run module_b.py, it will print "initial". However, if one > adds to the end of module_a.py this line: > > | change_value() > > The script module_b.py will print "changed". > > It seems that in the first case change_value() called in module_b.py > ignores the global statement. Is it so Why What happens in the second > case I really don't get it. > In Python, there are not any truly "global" variables as you're thinking of them. Instead, each module has it's own global space. You are tripping over the fact that module_a and module_b have their own separate global spaces. The variable "value" is global in module_a, and "change_value" will always refer to that variable. However, in module_b, when you from module_a import value, change_value you have created two new variables global to module_b that references values from the other module. Now running change_value (which changes "value" in module_a has no affect on the version of "value" in module_b. Your print is then printing value from module_b -- the unchanged version. If you truly want to examine value in module_a, the you have to access it as import module_a module_a.change_value() print module_a.value You can do both import module_a from module_a import change_value but that's probably confusing and generally considered a bad idea. Ideas: 1 If you want module_a to manage such a global variable, you could include functions for getting, and setting it, as well as your function for changing it's value. 2. You could also dispense with use of global values -- various OOP techniques could help there. Gary Herron >
VIEWS ON THIS POST

94

Posted on:

Monday 5th November 2012
View Replies!

RE: Accessing global namespace from module

On Jun 11, 11:02 am, reubendb wrote: > , > I am new to Python. I have the following question / problem. > I have a visualization software with command-line interface (CLI), > which essentially is a Python (v. 2.5) interpreter with functions > added to the global namespace. I would like to keep my own functions > in a separate module and then import that module to the main script > (that will be executed using the CLI interpreter). The problem is, I > cannot access the functions in the global namespace of the main script > from my module. Is there anyway to do that > > Here is an example of what I meant. The function AddPlot() and > DrawPlots() are added to the global namespace by the software CLI. If > I do this: > > mainscript.py: > --------------------------- > AddPlot("scatter", "coordinate") > # set other things here > DrawPlots() > > it works fine. But I want to be able to do this: > > myModule.py: > ---------------------- > def defaultScatterPlot(): > AddPlot("scatter", "coordinate") > #do other things > DrawPlots() > > and then in mainscript.py: > --------------------------------------- > import myModule > myModule.defaultScatterPlot() > > This won't work because myModule.py doesnot have access to AddPlot(). > How do I do something like this > > Thank you in advance for any help. > RDB > > -- > http://mail.python.org/mailman/listinfo/python-list Since the visulization software creator wasn't kind enough to bundle the drawing functions up into a module for you, you can just do it yourself. >>> import sys, new >>> plotModule = new.module( 'plot' ) >>> plotModule.AddPlot = AddPlot >>> plotModule.DrawPlots = DrawPlots >>> sys.modules[ 'plot' ] = plotModule Then, you can import your fake module from anywhere, and access its contents. >>> import plot >>> plot >>> plot.AddPlot Hope that helps. --------- John Krukoff jkrukoff@ltgc.com
VIEWS ON THIS POST

92

Posted on:

Monday 5th November 2012
View Replies!

RE: Accessing global namespace from module

> -----Original Message----- > From: python-list-bounces+jkrukoff=ltgc.com@python.org [mailtoython- > list-bounces+jkrukoff=ltgc.com@python.org] On Behalf Of Reuben D. > ardja > Sent: Monday, June 11, 2007 7:19 PM > To: python-list@python.org > Subject: Re: Accessing global namespace from module > > On Monday 11 June 2007 17:10:03 Gabriel Genellina wrote: > > En Mon, 11 Jun 2007 17:29:35 -0300, reubendb > escribi: > > > On Jun 11, 3:30 pm, "Gabriel Genellina" > > > > > > wrote: > > >> En Mon, 11 Jun 2007 15:18:58 -0300, reubendb > > >> > > >> escribi: > > >> > The problem is I don't define the functions AddPlot() and > DrawPlots(). > > >> > It's built into the python interpreter of the CLI version of the > > >> > program I mentioned, and they are defined on the main script. I > load > > >> > the main script using something like "software -cli -s > > >> > mainscript.py". > > >> > In the mainscript.py I import myModule, but of course myModule does > > >> > not have access to the functions defined in the global namespace of > > >> > mainscript.py. > > >> > > >> Don't you have some import statements at the top of mainscript.py > that > > >> are > > >> responsible for bringing AddPlot and DrawPlots into the current > > >> namespace > > >> Import the same things in your second module. > > > > > > No, I *don't* have any import statement mainscript.py. When using this > > > software's CLI, AddPlot and DrawPlots are available to me > > > automagically from mainscript.py. Hence my question: How do I make > > > this available from other module. Is there any way at all > > > > Yes: create your own module on-the-fly, using the recipe posted earlier > by > > John Krukoff. > > If there are many functions, try enumerating them all: > > > > import sys > > from types import ModuleType as module > > > > plotModule = module('plot') > > for key,value in globals().items(): > > if key[:2] != '__': > > setattr(plotModule, key, value) > > > > sys.modules['plot'] = plotModule > > Great ! That seems to work, thanks a lot. > One last question. Do I have to do this for ever script I write, or can I > put > this into separate file and "include" it somehow > I am going to have several mainscripts.py, and all is going to import > myModule > that will need access to this plots subroutine. It'll be great if I can > put > this trick on a single file that is included by the main scripts, to avoid > violating DRY principle. > >
VIEWS ON THIS POST

80

Posted on:

Monday 5th November 2012
View Replies!

Re: Syntax error in ".py" file and globals variable values notavailable.

On Wed, Aug 27, 2008 at 2:49 AM, Alexis Boutillier wrote: > > > I have a strange behaviour of python with pdb and import statement. > Here is the example code : > > file my1.py: > import my2 > > file my2.py: > a=5 > toto > > I intentionnaly put a syntax error in file my2.py. > > If I run "python -i my2.py" and run pdb I got : > NameError: name 'toto' is not defined >>>> import pdb >>>> pdb.pm() > -> toto >>>> print a > 5 > > If I run "python -i my1.py" and run pdb I got : > NameError: name 'toto' is not defined >>>> import pdb >>>> pdb.pm() > -> toto >>>> print a > None > > Why can't I get access to variable a in pdb when the process generating the > error came from an import statement > > With python 2.3.5, it works fine and in the two cases I get the correct > value of 5 for variable "a". > with python 2.43,2.5.1,2.5.2, it doesn't work and I get "None" value for > variable a. > > Somebody can explain me this behaviour > > >
VIEWS ON THIS POST

90

Posted on:

Wednesday 7th November 2012
View Replies!

Re: Syntax error in ".py" file and globals variable values notavailable.

Timothy Grant a crit : > On Wed, Aug 27, 2008 at 2:49 AM, Alexis Boutillier > wrote: >> >> >> I have a strange behaviour of python with pdb and import statement. >> Here is the example code : >> >> file my1.py: >> import my2 >> >> file my2.py: >> a=5 >> toto >> >> I intentionnaly put a syntax error in file my2.py. >> >> If I run "python -i my2.py" and run pdb I got : >> NameError: name 'toto' is not defined >>>>> import pdb >>>>> pdb.pm() >> -> toto >>>>> print a >> 5 >> >> If I run "python -i my1.py" and run pdb I got : >> NameError: name 'toto' is not defined >>>>> import pdb >>>>> pdb.pm() >> -> toto >>>>> print a >> None >> >> Why can't I get access to variable a in pdb when the process generating the >> error came from an import statement >> >> With python 2.3.5, it works fine and in the two cases I get the correct >> value of 5 for variable "a". >> with python 2.43,2.5.1,2.5.2, it doesn't work and I get "None" value for >> variable a. >> >> Somebody can explain me this behaviour >> >> >>
VIEWS ON THIS POST

82

Posted on:

Wednesday 7th November 2012
View Replies!

Syntax error in ".py" file and globals variable values not available.

I have a strange behaviour of python with pdb and import statement. Here is the example code : file my1.py: import my2 file my2.py: a=5 toto I intentionnaly put a syntax error in file my2.py. If I run "python -i my2.py" and run pdb I got : NameError: name 'toto' is not defined >>> import pdb >>> pdb.pm() -> toto >>> print a 5 If I run "python -i my1.py" and run pdb I got : NameError: name 'toto' is not defined >>> import pdb >>> pdb.pm() -> toto >>> print a None Why can't I get access to variable a in pdb when the process generating the error came from an import statement With python 2.3.5, it works fine and in the two cases I get the correct value of 5 for variable "a". with python 2.43,2.5.1,2.5.2, it doesn't work and I get "None" value for variable a. Somebody can explain me this behaviour
VIEWS ON THIS POST

93

Posted on:

Wednesday 7th November 2012
View Replies!

module global variables

hi to all! can i load a module passing to it, automatically and as default, all the caller's global variables to act as module's global variables
VIEWS ON THIS POST

78

Posted on:

Wednesday 7th November 2012
View Replies!

how to get module globals into a class ?

hello, this question may look a little weird, but I want to create library shells that are a simple as possible. So I've a module where one base class is defined, which looks like this (and might be complex) base_class_file.py class brick_base ( object ) : .... now I've a lot of library files, in each library file are a lot of classes, and each library-file, has some specific parameters, like "library_color", so something like this: library_file.py library_color = ... class brick_do_something1( brick_base ) : init : self.Library_Color = Library_Color .... class brick_do_something2( brick_base ) : init : self.Library_Color = Library_Color .... Now this works fine, ... .... but the statement "self.Library_Color = Library_Color" is completely redundant, because it should be in every class of every librray file. So I would like to move this statement to the base-class-file, but I can't figure out how to accomplish that.
VIEWS ON THIS POST

81

Posted on:

Wednesday 7th November 2012
View Replies!

Capturing global input?

I'd like to accept mouse gestures and keyboard shortcuts as input to a program. The nature of this program requires that these commands be issued regardless of the currently active window. Here's the rub: I need a platform-independent solution. Java supports with its MouseInfo class, but I'd like a Python equivalent without turning to Jython. Is this possible
VIEWS ON THIS POST

67

Posted on:

Wednesday 7th November 2012
View Replies!

Function to resize global numpy array interactively in ipython

I have a script with function definitions which I load into ipython for interactive use. These functions modify a global numpy array, whose size I need to be able to change interactively. I thus have a script which looks like this: from numpy import * def do_resize(N): global a a = resize(a, N) a = array([]) N=10; do_resize(N) print "Length of a is: ", len(a) N=20; do_resize(N) print "Length of a is: ", len(a) If I run this in ipython, using "run resize.py", it correctly outputs 10 and then 20. If I now type *interactively* N=30; do_resize(N), then the length of a is still 20, rather than 30 as I was hoping -- somehow I seem to be now dealing with a different copy of a Doing the same thing in idle works as I expect, i.e. interactively the size is changed to 30. Could somebody please explain what's going on, and how I solve the problem
VIEWS ON THIS POST

110

Posted on:

Wednesday 7th November 2012
View Replies!

Re: global name is not defined - but this is actually a function'sname

On 9/21/07, Mridula Ramesh wrote: > hi. > > i'm a beginner and i'm trying to get the hang of classes and functions. my > code looks like this: > > > > class showRecord(main): > def __init__(self): > global gmax > #now to create the screen by placing all the widgets > rt = Tk() > showbuttons() > #call the scroller to DoSomething > scroll() > > def showbuttons(self): > # NAVIGATION BAR------ > NavBut1 = Button(rt, text="|
VIEWS ON THIS POST

73

Posted on:

Wednesday 7th November 2012
View Replies!

UnboundLocalError on global variable

i have a problem, the source of which is probably the fact, that i have not understood how to declare global variables - I use the Jython compiler, but i think this is a Python issue... First of all, i don not use any classes in this module. The problem is, that i declare and instantiate some vars outside the functions (global ones), but when i use them inside the functions, i get an "UnboundLocalError" error. Here's the interesting part of the code: ========================================================================================== #imports .... #CONSTANTS ...... .... #connection to DB dbcursor_=db.cursor() #GLOBAL VARS entryList_={} cmterID_=0 //VARIABLE DECLARATION projID_=0 fileIDNumber_=0 Commiter_={} Commit_={} Project_={} ProjectVersion_={} def updateCommiterTable(Commiter): query="INSERT INTO Commiter (pk_cmterID,cmterName) VALUES ("+str(Commiter[0])+",\""+str(Commiter[1])+"\");" dbcursor_.execute(query) def updateCommitTable(Commit): query="INSERT INTO Commit (pk_cmitID,cmitTime,fk_cmterID,cmitProperties,cmitComment,cmitCommentLines,fk_projID) VALUES (" \ +str(Commit[0])+",\""+str(Commit[1])+"\","+str(Commit[2])+",\""+str(Commit[3])+"\",\""+str(Commit[4])+"\","+str(Commit[5])+","+str(Commit[6])+");" dbcursor_.execute(query) def updateProjectTable(Project): dbcursor_.execute("INSERT INTO Project (pk_projID,projName,projWebsite,projContactPoint,projSrcPath,projMailPath) VALUES (" \ +str(Project[0])+",\""+str(Project[1])+"\",\""+str(Project[2])+"\",\""+str(Project[3])+"\",\""+str(Project[4])+"\",\""+str(Project[5])+"\");") def updateProjectVersionTable(ProjectVersion): dbcursor_.execute("INSERT INTO ProjectVersion (pfk_projID,projName,projVersion) VALUES (" \ +str(ProjectVersion[0])+",\""+str(ProjectVersion[1])+"\",\""+str(ProjectVersion[2])+"\");"); def getLogsLoop(): while svnLogging_.getCurrentRevisionNumber()!=svnLogging_.getLatestRevisionNumber(): try: entryList_=svnLogging_.getNextLogs(PIVOT); except HeadRevisionReachedException: print "Attempting to go over the HEAD revision..." for entry in entryList_: print "processing new SVN entry..." processLogEntry(entry) entryList_.clear() def processLogEntry(entry): revision = int(entry.getRevision()) commiter = str(entry.getAuthor()) datetime = getTimeStamp(entry.getDate()) message = str(entry.getMessage()) Commiter_[0] = cmterID_ //HERE's THE PROBLEM Commiter_[1] = commiter updateCommiterTable(Commiter_) Commit_[0] = revision Commit_[1] = datetime Commit_[2] = cmterID_ Commit_[3] = "" #properties Commit_[4] = message Commit_[5] = getNumberOfLines(message) Commit_[6] = projID_ updateCommitTable(Commit_) ProjectVersion_[0]=projID_ ProjectVersion_[1]="" ProjectVersion_[2]="" updateProjectVersionTable(ProjectVersion_) Project_[0]=projID_ Project_[1]="" Project_[2]="" Project_[3]="" Project_[4]="" Project_[5]="" updateProjectTable(Project_) cmterID_+=1 projID_+1 ##############################HELPER##METHODS############################### .... ##############################HELPER##METHODS############################### getLogsLoop() ========================================================================================== And I get: ========================================================================================== Traceback (innermost last): File "ParseSVN2DB.py", line 182, in File "ParseSVN2DB.py", line 87, in getLogsLoop File "ParseSVN2DB.py", line 100, in processLogEntry UnboundLocalError: local: 'cmterID_' ========================================================================================== The things is, that cmterID_ HAS BEEN instantiated... I don't understand. Can somebody please explain
VIEWS ON THIS POST

53

Posted on:

Wednesday 7th November 2012
View Replies!

Re: Imported globals?

On Jul 27, 2007, at 10:56 PM, Gary Herron wrote: > The variable "value" is global in module_a, and "change_value" will > always refer to that variable. > > However, in module_b, when you from module_a import value, > change_value > you have created two new variables global to module_b that references > values from the other module. > Now running change_value (which changes "value" in module_a has no > affect on the version of "value" in module_b. Your print is then > printing value from module_b -- the unchanged version. Thank you, Gary, but I still have one question. What happens in the second case If I add a call to change_value() to module_a, the value in module_b is imported changed. Why What exactly does the import statement import in my example > Ideas: > 1 If you want module_a to manage such a global variable, you could > include functions for getting, and setting it, as well as your > function for changing it's value. > > 2. You could also dispense with use of global values -- various OOP > techniques could help there.
VIEWS ON THIS POST

42

Posted on:

Wednesday 7th November 2012
View Replies!

Re: problem with global var

Bruno Ferreira wrote: > When I execute the program _without_ the lines 10 and 11: > > 10 if len(topsquid) > 50: > 11 topsquid = topsquid[0:50] > > it runs perfectly. > > But if I execute the program ...
VIEWS ON THIS POST

49

Posted on:

Saturday 10th November 2012
View Replies!

Re: Calling global functions from a class?

Robert Dailey wrote: > I have the following python script: > > def __normalizePath( path ): > return osp.abspath( osp.normpath( path ) ) > > class AbsolutePath: > def __init__( self, root="" ): > _root = __normalizePath( root ) > ...
VIEWS ON THIS POST

63

Posted on:

Sunday 11th November 2012
View Replies!

Problem with global variables

Pythoners, I'm having trouble understanding the behavior of global variables in a code I'm writing. I have a file, test.py, with the following contents foo = [] def goo(): global foo foo = [] foo.append(2) def moo(): print foo In ...
VIEWS ON THIS POST

51

Posted on:

Sunday 11th November 2012
View Replies!

Re: how can I use exec with main module globals?

En Sat, 12 Jul 2008 16:15:36 -0300, Akathorn Greyhat escribi: > , this is my first message in the group. Welcome! > I'm spanish so my english sometimes is really bad, sorry =( > > I have a problem ...
VIEWS ON THIS POST

60

Posted on:

Sunday 11th November 2012
View Replies!

User-defined exception: "global name 'TestRunError' is not defined"

I'm using some legacy code that has a user-defined exception in it. The top level program includes this line from TestRunError import * It also imports several other modules. These other modules do not explicitly import TestRunError. TestRunError is raised ...
VIEWS ON THIS POST

51

Posted on:

Sunday 11th November 2012
View Replies!

global variables: to be or not to be

I've read 'global variables' are bad. The ones that are defined as 'global' inside a function/method. The argument that pops up every now and then is that they are hard to keep track of. I don't know Python well enough ...
VIEWS ON THIS POST

44

Posted on:

Sunday 11th November 2012
View Replies!