[issue24592] global var defined in module not returned by function

2015-07-08 Thread Steve Dower

Steve Dower added the comment:

You should start by posting this to python-list or StackOverflow, and I'd 
suggest including code that can actually be run - it's far more precise than 
pseudocode.

(Functions and modules get used a lot. It's far more likely there's a bug in 
your code than in Python's implementation.)

--
resolution:  - not a bug
stage:  - resolved
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue24592
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue24592] global var defined in module not returned by function

2015-07-08 Thread arthur

New submission from arthur:

defined global var, glob.myVar, in separated module
imported module containing glob.myVar

in function1, func1():
glob.myVar = 
func1Var = func2()

in function2, func2():
if (...):
glob.myVar+= abc 
func2() # call func2() again - recursive
else:
return glob.myVar

I always find:
func1Var is None = True

An obvious workaround is
func1Var = glob.myVar
which is fine

--
components: Windows
messages: 246460
nosy: arthur, paul.moore, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: global var defined in module not returned by function
type: behavior
versions: Python 3.6

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue24592
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: shortcut for large amount of global var declarations?

2010-05-10 Thread Lawrence D'Oliveiro
In message mailman.2771.1273327690.23598.python-l...@python.org, Alex Hall 
wrote:

 ... I have about fifteen vars in a function which have to be
 global.

Why not make them class variables, e.g.

class my_namespace :
var1 = ...
var2 = ...
#end my_namespace

def my_function(...) :
... can directly read/assign my_namespace.var1 etc here ...
#end my_function

Also has the benefit of minimizing pollution of the global namespace.
-- 
http://mail.python.org/mailman/listinfo/python-list


shortcut for large amount of global var declarations?

2010-05-08 Thread Alex Hall
Hi all,
I am sorry if this is the second message about this you get; I typed
this and hit send (on gmail website) but I got a 404 error, so I am
not sure if the previous message made it out or not.
Anyway, I have about fifteen vars in a function which have to be
global. Is there a faster and more space-efficient way of doing this
than putting each var on its own line; that is, fifteen global
varName declarations? Thanks.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shortcut for large amount of global var declarations?

2010-05-08 Thread MRAB

Alex Hall wrote:

Hi all,
I am sorry if this is the second message about this you get; I typed
this and hit send (on gmail website) but I got a 404 error, so I am
not sure if the previous message made it out or not.
Anyway, I have about fifteen vars in a function which have to be
global. Is there a faster and more space-efficient way of doing this
than putting each var on its own line; that is, fifteen global
varName declarations? Thanks.


'global' will accept multiple names:

def foo():
global a, b, c
...
--
http://mail.python.org/mailman/listinfo/python-list


Re: shortcut for large amount of global var declarations?

2010-05-08 Thread Jon Clements
On 8 May, 15:08, Alex Hall mehg...@gmail.com wrote:
 Hi all,
 I am sorry if this is the second message about this you get; I typed
 this and hit send (on gmail website) but I got a 404 error, so I am
 not sure if the previous message made it out or not.
 Anyway, I have about fifteen vars in a function which have to be
 global. Is there a faster and more space-efficient way of doing this
 than putting each var on its own line; that is, fifteen global
 varName declarations? Thanks.

 --
 Have a great day,
 Alex (msg sent from GMail website)
 mehg...@gmail.com;http://www.facebook.com/mehgcap

About 15 that *need* to be global; smells bad to me. However, you can
amend a function's .func_globals attribute. Just wouldn't be going
there myself. Why do you have this many? What's your use case?

Jon.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shortcut for large amount of global var declarations?

2010-05-08 Thread Alex Hall
On 5/8/10, Jon Clements jon...@googlemail.com wrote:
 On 8 May, 15:08, Alex Hall mehg...@gmail.com wrote:
 Hi all,
 I am sorry if this is the second message about this you get; I typed
 this and hit send (on gmail website) but I got a 404 error, so I am
 not sure if the previous message made it out or not.
 Anyway, I have about fifteen vars in a function which have to be
 global. Is there a faster and more space-efficient way of doing this
 than putting each var on its own line; that is, fifteen global
 varName declarations? Thanks.

 --
 Have a great day,
 Alex (msg sent from GMail website)
 mehg...@gmail.com;http://www.facebook.com/mehgcap

 About 15 that *need* to be global; smells bad to me. However, you can
 amend a function's .func_globals attribute.
How do you do this exactly?
 Just wouldn't be going there myself. Why do you have this many? What's your
 use case?
They are in a setOptions function in config.py, which reads from an
ini file and sets up all options for the program. All other files then
can read these options. For example, anyone else can import config,
then, if they are rounding a number, they can know how many places to
round to by looking at config.rnd. I have everything in a function
instead of being initialized upon importing since I offer a function
to reload the ini file if the user changes something. Eventually I
will have a gui for setting options, and that gui, to save options,
will write an ini file then call setOptions so all options are then
reset according to the newly created ini. If I do not make everything
in setOptions global, no other file seems able to read it; I get an
exception the first time another file tries to access a setting.
Thanks.

 Jon.

 --
 http://mail.python.org/mailman/listinfo/python-list



-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shortcut for large amount of global var declarations?

2010-05-08 Thread James Mills
On Sun, May 9, 2010 at 12:08 AM, Alex Hall mehg...@gmail.com wrote:
 Hi all,
 I am sorry if this is the second message about this you get; I typed
 this and hit send (on gmail website) but I got a 404 error, so I am
 not sure if the previous message made it out or not.
 Anyway, I have about fifteen vars in a function which have to be
 global. Is there a faster and more space-efficient way of doing this
 than putting each var on its own line; that is, fifteen global
 varName declarations? Thanks.

Using globals (global variables) is generally considered bad practise.

Consider instead using a class/object. You could for example
have a config object that is shared by other modules.

cheers
James
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shortcut for large amount of global var declarations?

2010-05-08 Thread Jon Clements
On 8 May, 16:03, Alex Hall mehg...@gmail.com wrote:
 On 5/8/10, Jon Clements jon...@googlemail.com wrote:

  On 8 May, 15:08, Alex Hall mehg...@gmail.com wrote:
  Hi all,
  I am sorry if this is the second message about this you get; I typed
  this and hit send (on gmail website) but I got a 404 error, so I am
  not sure if the previous message made it out or not.
  Anyway, I have about fifteen vars in a function which have to be
  global. Is there a faster and more space-efficient way of doing this
  than putting each var on its own line; that is, fifteen global
  varName declarations? Thanks.

  --
  Have a great day,
  Alex (msg sent from GMail website)
  mehg...@gmail.com;http://www.facebook.com/mehgcap

  About 15 that *need* to be global; smells bad to me. However, you can
  amend a function's .func_globals attribute.

 How do you do this exactly? Just wouldn't be going there myself. Why do you 
 have this many? What's your
  use case?

 They are in a setOptions function in config.py, which reads from an
 ini file and sets up all options for the program. All other files then
 can read these options. For example, anyone else can import config,
 then, if they are rounding a number, they can know how many places to
 round to by looking at config.rnd. I have everything in a function
 instead of being initialized upon importing since I offer a function
 to reload the ini file if the user changes something. Eventually I
 will have a gui for setting options, and that gui, to save options,
 will write an ini file then call setOptions so all options are then
 reset according to the newly created ini. If I do not make everything
 in setOptions global, no other file seems able to read it; I get an
 exception the first time another file tries to access a setting.
 Thanks.



  Jon.

  --
 http://mail.python.org/mailman/listinfo/python-list

 --
 Have a great day,
 Alex (msg sent from GMail website)
 mehg...@gmail.com;http://www.facebook.com/mehgcap

Umm, okay at least now we know the context.

Similar to what James suggested just have a dict object in your config
module called 'settings' or something and access that. I still prefer
the giveth rather than taketh approach though. But heck, if it
works, who cares?

Jon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shortcut for large amount of global var declarations?

2010-05-08 Thread Steven D'Aprano
On Sat, 08 May 2010 10:08:08 -0400, Alex Hall wrote:

 Hi all,
 I am sorry if this is the second message about this you get; I typed
 this and hit send (on gmail website) but I got a 404 error, so I am not
 sure if the previous message made it out or not. Anyway, I have about
 fifteen vars in a function which have to be global. Is there a faster
 and more space-efficient way of doing this than putting each var on its
 own line; that is, fifteen global varName declarations? Thanks.

global google, for_, global_, variables, considered, harmful



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Global var access in imported modules?

2008-08-27 Thread RgeeK
I have a main module doStuff.py and another module utility.py.  At the 
start of doStuff.py I call


   import utility.py

Then I also proceed to initiallize some global variables

sName = 

Then I create a class, some methods etc.  In one of the methods I assign
a value to my variable sName.  Then I call a function from within
my utility.py file:

 utility.makeOne(stuff)


Within my utility.py file, I define the makeOne function. But I want to 
use that same global variable sName  In utility.py I have tried to 
indicate that I'm using the global sName through the statement:


  global sName

But when I go to use the variable it still gives me an error:

  NameError: global name 'sName' is not defined

I thought perhaps I need to indicate 'globality' in my main module, so 
before I initiallized sName in doStuff.py I added:


global sName

But it doesn't help me.   I had this issue before and resolved it by 
declaring the variable global in the sub-module utility.py, but then I 
needed to reference it in my main module with a prefix:


 utility.sName = 

It's more verbose,and defining globals in a submodule seems backward.
But also, what if I need to access sName in another imported module, 
say otherstuff.py?   I would do my import otherstuff call in my main 
module, but would I have to put an import utility into the 
otherstuff.py file?


Is there some way I can define globals in my main module, and have them 
accessible in all my imported submodule?


As you can see I'm a little unsure about the global handling in a 
multi-module environment. Any suggestions appreciated. I've read 
http://docs.python.org/ref/naming.html but it hasn't enlightened me on 
this one.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Global var access in imported modules?

2008-08-27 Thread Fredrik Lundh

RgeeK wrote:

I have a main module doStuff.py and another module utility.py.  At the 
start of doStuff.py I call


   import utility.py


that tries to import a module named py from the package utility.


Then I also proceed to initiallize some global variables

sName = 


Within my utility.py file, I define the makeOne function. But I want to 
use that same global variable sName  In utility.py I have tried to 
indicate that I'm using the global sName through the statement:


  global sName


the global directive in Python is used *inside* a function or method 
to indicate that a given name is not local.


Python doesn't have program-wide global variables; if you need that, 
create a support module and import that module everywhere you need to 
access those variables:


# file: globalvars.py
sName = 

# file: myprogram.py
import globalvars
print globalvars.sName

etc.

/F

--
http://mail.python.org/mailman/listinfo/python-list


Re: Global var access in imported modules?

2008-08-27 Thread Rgg

Fredrik Lundh wrote:

   import utility.py

that tries to import a module named py from the package utility.


oops - that was just a typo in my post - I meant of course import utility


Python doesn't have program-wide global variables; if you need that, 
create a support module and import that module everywhere you need to 
access those variables:


# file: globalvars.py
sName = 

# file: myprogram.py
import globalvars
print globalvars.sName

etc.

/F



That's news - thanks, I didn't realize that there just wasn't the 
concept of program-wide globals.  The support module idea sounds like a 
path forward.


-R.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Global var access in imported modules?

2008-08-27 Thread RgeeK

Fredrik Lundh wrote:
import utility.py
 that tries to import a module named py from the package utility.

oops - that was just a typo in my post - I meant of course import utility

 Python doesn't have program-wide global variables; if you need that,
 create a support module and import that module everywhere you need to
 access those variables:

 # file: globalvars.py
 sName = 

 # file: myprogram.py
 import globalvars
 print globalvars.sName

 etc.

 /F


That's news - thanks, I didn't realize that there just wasn't the 
concept of program-wide globals.  The support module idea sounds like a 
path forward.


-R.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Global var access in imported modules?

2008-08-27 Thread RgeeK

Dennis Lee Bieber wrote:

On Wed, 27 Aug 2008 16:21:03 -0400, RgeeK [EMAIL PROTECTED]
declaimed the following in comp.lang.python:

I have a main module doStuff.py and another module utility.py.  At the 
start of doStuff.py I call


import utility.py


I hope not...   import utility  no .py

Then I also proceed to initiallize some global variables


Python does not have global variables. Names belong within a module
(or within functions defined within the module).


sName = 

Then I create a class, some methods etc.  In one of the methods I assign
a value to my variable sName.  Then I call a function from within
my utility.py file:

  utility.makeOne(stuff)


Within my utility.py file, I define the makeOne function. But I want to 
use that same global variable sName  In utility.py I have tried to 
indicate that I'm using the global sName through the statement:


   global sName


The global statement is only used within functions (def blocks) to
indicate that writes to the specified name are to modify the MODULE
level version of the name, otherwise a write modifies a function local
version of the name (you don't need global for read-only access of
names, the search for names first looks inside the function, then out to
the module)
 

But when I go to use the variable it still gives me an error:

   NameError: global name 'sName' is not defined

I thought perhaps I need to indicate 'globality' in my main module, so 
before I initiallized sName in doStuff.py I added:


global sName

But it doesn't help me.   I had this issue before and resolved it by 
declaring the variable global in the sub-module utility.py, but then I 
needed to reference it in my main module with a prefix:


  utility.sName = 

It's more verbose,and defining globals in a submodule seems backward.
But also, what if I need to access sName in another imported module, 
say otherstuff.py?   I would do my import otherstuff call in my main 
module, but would I have to put an import utility into the 
otherstuff.py file?



If you really need globals the common solution is to create a
module such as myglobals, define all the shared names within that
module, and import that module where ever you need access to one of the
names. And yes, you will need to qualify all those names with the module
name (though you can do things like:

import myglobals as mg

and then use

mg.somename

instead of

myglobals.somename)
 



Thanks for the reply.  Good to see that approach has broad support :) 
I'll do that.  I like the idea of a nice short alias for the import to 
keep the qualifications brief.


Ross.
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with global var

2008-01-04 Thread Peter Otten
Bruno Ferreira wrote:

 I wrote a very simple python program to generate a sorted list of
 lines from a squid access log file.

Now that your immediate problem is solved it's time to look at the heapq
module. It solves the problem of finding the N largest items in a list
much more efficiently. I think the following does the same as your code:

import heapq

def key(record):
return int(record[4])

logfile = open(squid_access.log, r)
records = (line.split() for line in logfile)
topsquid = heapq.nlargest(50, records, key=key)

for record in topsquid:
print record[4]

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with global var

2008-01-04 Thread Bruno Ferreira
Hello all,

Amazing :)

The program is working properly now,  the code is much better and I
learned a bit more Python.

Thank  you all, guys.

Bruno.

2008/1/4, Peter Otten [EMAIL PROTECTED]:
 Bruno Ferreira wrote:

  I wrote a very simple python program to generate a sorted list of
  lines from a squid access log file.

 Now that your immediate problem is solved it's time to look at the heapq
 module. It solves the problem of finding the N largest items in a list
 much more efficiently. I think the following does the same as your code:

 import heapq

 def key(record):
 return int(record[4])

 logfile = open(squid_access.log, r)
 records = (line.split() for line in logfile)
 topsquid = heapq.nlargest(50, records, key=key)

 for record in topsquid:
 print record[4]

 Peter
 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


problem with global var

2008-01-03 Thread Bruno Ferreira
Hi,

I wrote a very simple python program to generate a sorted list of
lines from a squid access log file.

Here is a simplified version:

##
1  logfile = open (squid_access.log, r)
2  topsquid = [[0, 0, 0, 0, 0, 0, 0]]
3
4  def add_sorted (list):
5 for i in range(50):
6  if int(list[4])  int(topsquid[i][4]):
7  topsquid.insert(i,list)
8  break
8  # Max len = 50
10 if len(topsquid)  50:
11 topsquid = topsquid[0:50]
12
13 while True:
14 logline = logfile.readline()
15 linefields = logline.split()
16
17 if logline != :
18 add_sorted (linefields)
19 else:
20 break
21
22 for i in range (len(topsquid)):
23 print topsquid[i][4]


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 _with_ those lines, this exception is thrown:

[EMAIL PROTECTED]:~$ python topsquid.py
Traceback (most recent call last):
  File topsquid.py, line 20, in module
add_sorted (linefields)
  File topsquid.py, line 6, in add_sorted
if int(list[4])  int(topsquid[i][4]):
UnboundLocalError: local variable 'topsquid' referenced before assignment


Note that now the error shown is not related with the lines 10 and 11,
but wiht a line prior to them.

Any hints?

-- 
Bruno A. C. Ferreira
Linux Registered User #181386
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with global var

2008-01-03 Thread Matt Nordhoff
Bruno Ferreira wrote:
 Hi,
 
 I wrote a very simple python program to generate a sorted list of
 lines from a squid access log file.
 
 Here is a simplified version:
 
 ##
 1  logfile = open (squid_access.log, r)
 2  topsquid = [[0, 0, 0, 0, 0, 0, 0]]
 3
 4  def add_sorted (list):

Don't call your variable list. There's already the built-in type list.

 5 for i in range(50):

You should probably use xrange here.

 6  if int(list[4])  int(topsquid[i][4]):
 7  topsquid.insert(i,list)
 8  break
 8  # Max len = 50
 10 if len(topsquid)  50:
 11 topsquid = topsquid[0:50]

I'd just use [:50], the 0 is implied.

 13 while True:
 14 logline = logfile.readline()
 15 linefields = logline.split()
 16
 17 if logline != :
 18 add_sorted (linefields)
 19 else:
 20 break

for logline in logfile:
if logline:
linefields = logline.split()
add_sorted(linefields)
else:
break

 22 for i in range (len(topsquid)):
 23 print topsquid[i][4]

for i in topsquid:
print i[4]

(You probably want to use a name other than i then.)

 

 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 _with_ those lines, this exception is thrown:
 
 [EMAIL PROTECTED]:~$ python topsquid.py
 Traceback (most recent call last):
   File topsquid.py, line 20, in module
 add_sorted (linefields)
   File topsquid.py, line 6, in add_sorted
 if int(list[4])  int(topsquid[i][4]):
 UnboundLocalError: local variable 'topsquid' referenced before assignment
 
 
 Note that now the error shown is not related with the lines 10 and 11,
 but wiht a line prior to them.
 
 Any hints?

Basically, you're trying to read the global variable topsquid, and
then you're trying to define a local variable topsquid. Python doesn't
like that. Declare it as global by adding global topsquid to the top
of the function.
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with global var

2008-01-03 Thread wes
Bruno Ferreira wrote:
 Hi,
 
 I wrote a very simple python program to generate a sorted list of
 lines from a squid access log file.
 
 Here is a simplified version:
 
 ##
 1  logfile = open (squid_access.log, r)
 2  topsquid = [[0, 0, 0, 0, 0, 0, 0]]
 3
 4  def add_sorted (list):
 global topsquid
 5 for i in range(50):
 6  if int(list[4])  int(topsquid[i][4]):
 7  topsquid.insert(i,list)
 8  break
 8  # Max len = 50
 10 if len(topsquid)  50:
 11 topsquid = topsquid[0:50]
 12
 13 while True:
 14 logline = logfile.readline()
 15 linefields = logline.split()
 16
 17 if logline != :
 18 add_sorted (linefields)
 19 else:
 20 break
 21
 22 for i in range (len(topsquid)):
 23 print topsquid[i][4]
 
 
 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 _with_ those lines, this exception is thrown:
 
 [EMAIL PROTECTED]:~$ python topsquid.py
 Traceback (most recent call last):
   File topsquid.py, line 20, in module
 add_sorted (linefields)
   File topsquid.py, line 6, in add_sorted
 if int(list[4])  int(topsquid[i][4]):
 UnboundLocalError: local variable 'topsquid' referenced before assignment
 
 
 Note that now the error shown is not related with the lines 10 and 11,
 but wiht a line prior to them.
 
 Any hints?
 

Try line 4 add.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with global var

2008-01-03 Thread Diez B. Roggisch
Bruno Ferreira wrote:

 Hi,
 
 I wrote a very simple python program to generate a sorted list of
 lines from a squid access log file.
 
 Here is a simplified version:
 
 ##
 1  logfile = open (squid_access.log, r)
 2  topsquid = [[0, 0, 0, 0, 0, 0, 0]]
 3
 4  def add_sorted (list):
 5 for i in range(50):
 6  if int(list[4])  int(topsquid[i][4]):
 7  topsquid.insert(i,list)
 8  break
 8  # Max len = 50
 10 if len(topsquid)  50:
 11 topsquid = topsquid[0:50]
 12
 13 while True:
 14 logline = logfile.readline()
 15 linefields = logline.split()
 16
 17 if logline != :
 18 add_sorted (linefields)
 19 else:
 20 break
 21
 22 for i in range (len(topsquid)):
 23 print topsquid[i][4]
 
 
 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 _with_ those lines, this exception is thrown:
 
 [EMAIL PROTECTED]:~$ python topsquid.py
 Traceback (most recent call last):
   File topsquid.py, line 20, in module
 add_sorted (linefields)
   File topsquid.py, line 6, in add_sorted
 if int(list[4])  int(topsquid[i][4]):
 UnboundLocalError: local variable 'topsquid' referenced before assignment
 
 
 Note that now the error shown is not related with the lines 10 and 11,
 but wiht a line prior to them.
 
 Any hints?

Use 

def add_sorted(list):
   global topsquid
   ...

to make topsquid a global variable to add_sorted. Otherwise python sees that
it gets referred by in the if-statement before assigning to it, thus
resulting in the error you see. 

The reason for this is that a (limited) static analysis of python-code is
performed to determine which variables are local to a function and which
not. The criteria essentially is the appearance on the left-hand-side of an
expression makes a variable (or name) local to that function. Which makes
it require the explicit global declaration.

Apart from that there are quite a few things worth mentioning in your code:

 - don't shadow built-in names like list

 - it's superfluous to do

for i in xrange(len(some_list)):
.. some_list[i] ..

as you do, unless you need the index. Instead do

for element in some_list:
   ... element ...

If you need an index, do 

for i, element in enumerate(some_list):
   ...

 - don't use range, use xrange if you don't need a list but rather 
   want to enumerate indices.

 - the while-loop is superfluous as well, just do

for line in logfile:
  ...

or if your python is older do

for line in logfile.xreadlines():
  ...

Diez

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with global var

2008-01-03 Thread Fredrik Lundh
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 _with_ those lines, this exception is thrown:
 
 [EMAIL PROTECTED]:~$ python topsquid.py
 Traceback (most recent call last):
   File topsquid.py, line 20, in module
 add_sorted (linefields)
   File topsquid.py, line 6, in add_sorted
 if int(list[4])  int(topsquid[i][4]):
 UnboundLocalError: local variable 'topsquid' referenced before assignment

Python uses static analysis to determine if a variable is local to a 
function; somewhat simplified, if you assign to the variable inside the 
function, *all* uses of that variable inside the function will be 
considered local.  for the full story, see:

 http://docs.python.org/ref/naming.html

to fix this, you can insert a global declaration at the top of the

 def add_sorted (list):
 global topsquid # mark topsquid as global in this function
 ...

in this case, you can also avoid the local assignment by modifying the 
list in place;

 if len(topsquid)  50:
 topsquid[:] = topsquid[0:50]

or, as a one-liner:

 del topsquid[50:]

/F

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with global var

2008-01-03 Thread Steven D'Aprano
On Thu, 03 Jan 2008 11:38:48 -0300, Bruno Ferreira wrote:

 Hi,
 
 I wrote a very simple python program to generate a sorted list of lines
 from a squid access log file.
 
 Here is a simplified version:
 
 ##
 1  logfile = open (squid_access.log, r) 
 2  topsquid = [[0, 0, 0, 0, 0, 0, 0]]

[snip]


Others have already solved the immediate problem, but a much better 
design would be to avoid using a global variable in the first place.



def add_sorted(alist, data):
Add figures from alist to collated data and return data.
# do your processing here...
return data



topsquid=[[0, 0, 0, 0, 0, 0, 0]]
for line in logfile:
linefields = logline.split()
topsquid = add_sorted(linefields, topsquid)




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Count nb call of a function, without global var or decorator

2007-02-06 Thread Duncan Booth
Méta-MCI [EMAIL PROTECTED] wrote:

 Example, with meta-data (attributs of function) :
 
 def ff(this):
 try:
 this.count=this.count+1
 except:
 this.count=1
 a=1
 b=2
 c=a+b
 
 ff(ff)
 fa=ff
 ff(ff)
 fa(fa)
 print ff.count
 
 
 
 How to improve that?

If I've managed to guess what you are asking, you want to use a class:

 class Ff:
def __init__(self):
self.count = 0
def __call__(self, notused):
self.count += 1
a, b = 1, 2
c = a+b
return c


 ff = Ff()
 fa = Ff()
 ff(ff)
3
 ff.count
1
 fa.count
0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Count nb call of a function, without global var or decorator

2007-02-05 Thread M�ta-MCI
Re!

I can do :

def ff():
this=ff
try:
this.count=this.count+1
except:
this.count=1
a=1
b=2
c=a+b

ff()
fa=ff
ff()
fa()

print ff.count


But that use, inside the function, the litteral name of the function; and I 
want no use litteral name (inside)

@+

Michel Claveau




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Count nb call of a function, without global var or decorator

2007-02-05 Thread Bjoern Schliessmann
Méta-MCI wrote:

 Example, with meta-data (attributs of function) :

Apart from asking what counting nb call of a function means, I
wonder why you didn't use an iterator?

 @-salutations

@-less Regards,


Björn

-- 
BOFH excuse #65:

system needs to be rebooted

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Count nb call of a function, without global var or decorator

2007-02-05 Thread M�ta-MCI
Re!

 why you didn't use an iterator?

If the iterator is extern (to the function), it's like decorator, or global 
var.
If it is internal, it's huge, compare to  this.count=this.count+1  (or 
this.count+=1)


@+

Michel Claveau



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Count nb call of a function, without global var or decorator

2007-02-05 Thread Bjoern Schliessmann
Méta-MCI wrote:

 If the iterator is extern (to the function), it's like decorator,
 or global var.

Please excuse me, I don't understand your point. I'm not even sure
if both of us speak of the same iterators.

 If it is internal, it's huge, compare to  this.count=this.count+1 
 (or this.count+=1)

In which way huge? If you want top notch performance you should use
a C extension anyway ...

Regards,


Björn

-- 
BOFH excuse #339:

manager in the cable duct

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global var

2005-02-21 Thread Jeff Shannon
Nick Coghlan wrote:
Michael Hoffman wrote:
raver2046 wrote:
How to have a global var in python ?
global var will give you a global variable named var.
Whether this advice is correct or not depends greatly on what the OP 
means by 'global' :)

Module global, it's right, application global it's wrong. Given the 
nature of the question, I suspect the latter.
And even there, one must be careful.  global var won't really give you 
a global variable; it will cause the name var, when used locally, to 
refer to a pre-existing module-level reference var.  No variables are 
actually created in the execution of global var.

Jeff Shannon
--
http://mail.python.org/mailman/listinfo/python-list


Re: global var

2005-02-19 Thread Nick Coghlan
Michael Hoffman wrote:
raver2046 wrote:
How to have a global var in python ?

global var will give you a global variable named var.
Whether this advice is correct or not depends greatly on what the OP means by 
'global' :)

Module global, it's right, application global it's wrong. Given the nature of 
the question, I suspect the latter.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


global var

2005-02-17 Thread raver2046
hello,

How to have a global var in python ?

thank you.

raver2046
http://raver2046.ath.cx


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global var

2005-02-17 Thread Michael Hoffman
raver2046 wrote:
How to have a global var in python ?
global var will give you a global variable named var.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: global var

2005-02-17 Thread Steven Bethard
raver2046 wrote:
How to have a global var in python ?
You can, but you probably don't want to.  What's your use case?  Example 
code and what you'd like it to do would be helpful.

STeVe
--
http://mail.python.org/mailman/listinfo/python-list