473,699 Members | 2,570 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getting global variables from dictionary

global_vars.py has the global variables
set_var.py changes one of the values on the global variables (don't
close it or terminate)
get_var.py retrieves the recently value changed (triggered right after
set_var.py above)

Problem: get_var.py retrieves the old value, the built-in one but not
the recently changed value in set_var.py.

What am I doing wrong?

----global_vars.py---
#!/usr/bin/python

class Variables :
def __init__(self) :
self.var_dict = {"username": "original username"}
---set_var.py ---
#!/usr/bin/python

import time
import global_vars

global_vars.Var iables().var_di ct["username"] = "new username"
time.sleep(10) #give enough time to trigger get_var.py
---get_var.py ---
#!/usr/bin/python
import global_vars
print global_vars.Var iables().var_di ct.get("usernam e")
Sep 27 '08 #1
4 2376
On Sep 26, 9:01*pm, icarus <rsa...@gmail.c omwrote:
global_vars.py has the global variables
set_var.py changes one of the values on the global variables (don't
close it or terminate)
get_var.py retrieves the recently value changed (triggered right after
set_var.py above)

Problem: get_var.py retrieves the old value, the built-in one but not
the recently changed value in set_var.py.

What am I doing wrong?

----global_vars.py---
#!/usr/bin/python

class Variables :
* * * * def __init__(self) :
* * * * * * * * self.var_dict = {"username": "original username"}

---set_var.py ---
#!/usr/bin/python

import time
import global_vars

global_vars.Var iables().var_di ct["username"] = "new username"
time.sleep(10) * #give enough time to trigger get_var.py

---get_var.py ---
#!/usr/bin/python
import global_vars
print global_vars.Var iables().var_di ct.get("usernam e")
Are these separate processes?
Sep 27 '08 #2
When you do "Variables( )" in your code, you're making a new instance
of that class that has no relation to any other instances. This is the
cause of your problem. To just reference a class, use just
"Variables" . But that doesn't help in this case because var_dict is an
instance variable, not a class variable.

On Fri, Sep 26, 2008 at 7:01 PM, icarus <rs****@gmail.c omwrote:
global_vars.py has the global variables
No it doesn't, it just defines a class. The class itself (but NOT its
instances) is a module-level global.
set_var.py changes one of the values on the global variables (don't
close it or terminate)
No, it just instanciates the Variables class and then manipulates the
instance, which is then GC-ed because it's no longer referenced
anywhere, even in set_var.
get_var.py retrieves the recently value changed (triggered right after
set_var.py above)
No, it creates an entirely new instance of Variables and then fetches
the value from that instance (which is still using the default value
because this new instance has never been modified).
>
Problem: get_var.py retrieves the old value, the built-in one but not
the recently changed value in set_var.py.

What am I doing wrong?
Try just making var_dict a module-level variable in global_vars.py and
then manipulating that rather than this unnecessary mucking about with
Variables(). Alternatively, make var_dict a *class* variable of
Variables by removing it from __init__ and just putting 'var_dict =
{"username": "original username"}' in the raw class body of Variables;
And then remove the parentheses after Variables as I mentioned in the
beginning.

Regards,
Chris
>
----global_vars.py---
#!/usr/bin/python

class Variables :
def __init__(self) :
self.var_dict = {"username": "original username"}
---set_var.py ---
#!/usr/bin/python

import time
import global_vars

global_vars.Var iables().var_di ct["username"] = "new username"
time.sleep(10) #give enough time to trigger get_var.py
---get_var.py ---
#!/usr/bin/python
import global_vars
print global_vars.Var iables().var_di ct.get("usernam e")
--
http://mail.python.org/mailman/listinfo/python-list
--
Follow the path of the Iguana...
http://rebertia.com
Sep 27 '08 #3
icarus <rs****@gmail.c omwrites:
global_vars.py has the global variables
set_var.py changes one of the values on the global variables (don't
close it or terminate)
get_var.py retrieves the recently value changed (triggered right after
set_var.py above)

Problem: get_var.py retrieves the old value, the built-in one but
not the recently changed value in set_var.py.
That's because you're making a new instance each time; each instance
carries its own state.

For a collection of attributes that should share state, probably the
simplest way is to use attributes of a module.
----global_vars.py---
#!/usr/bin/python

class Variables :
def __init__(self) :
self.var_dict = {"username": "original username"}
These aren't "global variables"; they still need to be imported, like
anything else from a module. Better to name the module by intent; e.g.
if these are configuration settings, a module name of 'config' might
be better.

Also, this module presumably isn't intended to be run as a program;
don't put a shebang line (the '#!' line) on files that aren't run as
programs.

===== config.py =====
# -*- coding: utf-8 -*-

# Name of the front-end user
username = "original username"

# Amount of wortzle to deliver
wortzle_amount = 170
=====
---set_var.py ---
#!/usr/bin/python

import time
import global_vars

global_vars.Var iables().var_di ct["username"] = "new username"
time.sleep(10) #give enough time to trigger get_var.py
===== set_config.py =====
# -*- coding: utf-8 -*-

import config

def set_user():
config.username = "new username"
=====
---get_var.py ---
#!/usr/bin/python
import global_vars
print global_vars.Var iables().var_di ct.get("usernam e")
===== get_config.py =====
# -*- coding: utf-8 -*-

import config

def get_user():
return config.username
=====
The 'config' module, imported by both of the other modules, maintains
state:
>>import config
print config.username
original username
>>import set_config
set_config.se t_user()
print config.username
new username
>>import get_config
print get_config.get_ user()
new username

--
\ “You can't have everything; where would you put it?” —Steven |
`\ Wright |
_o__) |
Ben Finney
Sep 27 '08 #4
On Sep 26, 10:01*pm, icarus <rsa...@gmail.c omwrote:
global_vars.py has the global variables
set_var.py changes one of the values on the global variables (don't
close it or terminate)
get_var.py retrieves the recently value changed (triggered right after
set_var.py above)

Problem: get_var.py retrieves the old value, the built-in one but not
the recently changed value in set_var.py.

What am I doing wrong?

----global_vars.py---
#!/usr/bin/python

class Variables :
* * * * def __init__(self) :
* * * * * * * * self.var_dict = {"username": "original username"}

---set_var.py ---
#!/usr/bin/python

import time
import global_vars

global_vars.Var iables().var_di ct["username"] = "new username"
time.sleep(10) * #give enough time to trigger get_var.py

---get_var.py ---
#!/usr/bin/python
import global_vars
print global_vars.Var iables().var_di ct.get("usernam e")
First off, you don't import the set_var module anywhere; how do you
expect the value to change? Second, every time you do
"global_vars.Va riables()" you create a brand new Variables() instance,
initialized with the original var_dict. The Variables() instance you
create at set_var.py is discarded in the very next line. Third, I have
no idea why you put the "time.sleep(10) " there.

By the way, Python is not Java; you don't have to make classes for
everything. A working version of your example would be:

----global_vars.py---

var_dict = {"username": "original username"}

---set_var.py ---
import global_vars
global_vars.var _dict["username"] = "new username"

---get_var.py ---
import global_vars
import set_var
print global_vars.var _dict.get("user name")

$ python get_var.py
new username
HTH,
George
Sep 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
16746
by: Fuming Wang | last post by:
Hi, I have several modules that need to access global variables among them. I can do that by import modules: module A: gA = 'old' module B: import A
5
16005
by: ruari mactaggart | last post by:
how do I assign a value to a variable inside a function then use it in the main body ? i am trying to unpickle a dictionary in a function to use it in the program ruari
8
2344
by: alex | last post by:
Hi, is it possible to create 'global' variables that can be seen in all other classes? Alex
0
1448
by: Joe Blow via DotNetMonster.com | last post by:
Hello, I have a design problem involving class instances as global variables. To give you my background, I've programmed lots in Java, and most of it has been large class structures. I'm learning c# the hard way, but the similarities to Java are very helpful. However, in this case they are hurting, because I can't figure out the best way to store a class that can be accessed across the scope of an ASP.NET application. To begin with,...
5
14800
by: David Rasmussen | last post by:
If I have a string that contains the name of a function, can I call it? As in: def someFunction(): print "Hello" s = "someFunction" s() # I know this is wrong, but you get the idea... /David
1
2696
by: Crutcher | last post by:
I've been playing with dictionary subtypes for custom environments, and I encountered a strange interaction between exec, dictionary subtypes, and global variables. I've attached a test program, but first I'd like to give some background. Python uses dictionary objects as symbol tables in it's execution contexts. Since these objects used to be basic types, which were not subclassable, some of the interpreter code accessed them using...
4
2273
by: DaveM | last post by:
Although I've programmed for fun - on and off - since the mid 70's, I'm definitely an OO (and specifically Python) beginner. My first question is about global variables. Are they, as I'm starting to suspect, a sin against God or just best avoided? Having got my current application working using them, I'm not sure whether I want to refactor it, but equally, I'd like to write the best code I can. Secondly (and this is related), if you...
7
2331
bvdet
by: bvdet | last post by:
I provide shop drawings to structural steel fabricators with SDS/2 software (http://sds2.com) by Design Data (DD). I am not a programmer by education or trade and started writing scripts about 5 years ago. DD has a script interface with Python in the 3D model which is very useful in production. Part of the Python interface includes a dialog box class: dlg1 = Dialog('Dialog Box Title')Method dlg1.done() returns a dictionary. I am exporting the...
3
1850
by: Mr.SpOOn | last post by:
Hi, 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 fine. I was just thinking if it wasn't better to use class variables.
0
8689
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8618
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8916
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8885
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6534
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4376
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2010
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.