473,795 Members | 2,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Global module variables as default parameters

Hi, list...

I wondered if it's possible to use global (module) variables as default
parameters. A simple working example:

----------------------------------------
#!/usr/bin/python

globalvar = 123

def test(foo=global var):
print foo

test()
----------------------------------------

Running this script prints "123". That's what I expected.

Now I'm trying the same thing in a module context. A non-working example:

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

import TestModule

TestModule.glob alvar = 123
TestModule.def1 ()
TestModule.def2 ()
----------------------------------------

TestModule.py
----------------------------------------
globalvar = 0

def def1():
print globalvar

def def2(foo=global var):
print foo
----------------------------------------

Running the test.py script prints "123" and "0". So accessing the globalvar
in def1() works. But if I try to use the global variable as a default
parameter in def2() it uses the default "0". What is the difference
between these two? Are there contexts of default parameters?

Thanks for any enlightenment.

Christoph
Sep 22 '06 #1
5 1515
In <ma************ *************** ***********@pyt hon.org>, Christoph Haas
wrote:
TestModule.py
----------------------------------------
globalvar = 0

def def1():
print globalvar

def def2(foo=global var):
print foo
----------------------------------------

Running the test.py script prints "123" and "0". So accessing the globalvar
in def1() works. But if I try to use the global variable as a default
parameter in def2() it uses the default "0". What is the difference
between these two? Are there contexts of default parameters?
Default parameters are evaluated *once* when the ``def`` is executed. So
in `def2` the value of `foo` won't be looked up when calling the function
as it is already bound to the value 0.

Ciao,
Marc 'BlackJack' Rintsch
Sep 22 '06 #2
Christoph Haas wrote:
Hi, list...

I wondered if it's possible to use global (module) variables as default
parameters. A simple working example:

----------------------------------------
#!/usr/bin/python

globalvar = 123

def test(foo=global var):
print foo

test()
----------------------------------------

Running this script prints "123". That's what I expected.

Now I'm trying the same thing in a module context. A non-working example:

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

import TestModule

TestModule.glob alvar = 123
TestModule.def1 ()
TestModule.def2 ()
----------------------------------------

TestModule.py
----------------------------------------
globalvar = 0

def def1():
print globalvar

def def2(foo=global var):
print foo
----------------------------------------

Running the test.py script prints "123" and "0". So accessing the
globalvar in def1() works. But if I try to use the global variable as a
default parameter in def2() it uses the default "0". What is the
difference between these two? Are there contexts of default parameters?
Yes, and that context is the function definition which is executable code,
too. Whatever the variable 'right' in a statement like

def f(left=right): ...

is bound to when the def is executed will become the default for the 'left'
argument. This should become clear when you create more than one function
with the same
>>fs = []
for i in range(3):
.... def f(i=i): print i
.... fs.append(f)
....
>>for f in fs: f()
....
0
1
2

Use a sentinel when you don't want that behaviour:

def f(foo=None):
if foo is None: foo = globalvar
# ...

Peter
Sep 22 '06 #3
>>>>"Christop h" == Christoph Haas <em***@christop h-haas.dewrites:

ChristophHi, list... I wondered if it's possible to use global
Christoph(modul e) variables as default parameters. A simple
Christophworkin g example:

Christoph----------------------------------------
Christoph#!/usr/bin/python

Christophglobal var = 123

Christophdef test(foo=global var): print foo

kwargs defaults are initialized a module load time, not at function
call time. The standard idiom is

def test(foo=None):
if foo is None: foo = globalvar
print foo

JDH
Sep 22 '06 #4
John Hunter wrote:
>>>>>>"Christop h" == Christoph Haas <em***@christop h-haas.dewrites:


ChristophHi, list... I wondered if it's possible to use global
Christoph(modul e) variables as default parameters. A simple
Christophworkin g example:

Christoph----------------------------------------
Christoph#!/usr/bin/python

Christophglobal var = 123

Christophdef test(foo=global var): print foo

kwargs defaults are initialized a module load time, not at function
call time. The standard idiom is

def test(foo=None):
if foo is None: foo = globalvar
print foo

JDH
That's true when the functions are declared at the outer level of the
module, but don't overlook the fact that a function can be declared
inside another function or method call (and even returned as (part of)
the result of that call).

It would be more accurate to say that the default argument values are
bound when the def statement is executed.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 23 '06 #5
Thanks to all who answered.

On Friday 22 September 2006 17:28, Marc 'BlackJack' Rintsch wrote:
Christoph Haas wrote:
TestModule.py
----------------------------------------
globalvar = 0

def def1():
print globalvar

def def2(foo=global var):
print foo
----------------------------------------

Running the test.py script prints "123" and "0". So accessing the
globalvar in def1() works. But if I try to use the global variable as
a default parameter in def2() it uses the default "0". What is the
difference between these two? Are there contexts of default
parameters?

Default parameters are evaluated *once* when the ``def`` is executed.
So in `def2` the value of `foo` won't be looked up when calling the
function as it is already bound to the value 0.
Now that you point me to it it's pretty obvious indeed. I always forget
that the 'def's are executed at load time, too.

Peter/John: in fact I already used a sentinel like you proposed as
a "workaround ". So there is just one sensible way to do it. Again.

Kindly
Christoph
Sep 23 '06 #6

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

Similar topics

59
3949
by: seberino | last post by:
I've heard 2 people complain that word 'global' is confusing. Perhaps 'modulescope' or 'module' would be better? Am I the first peope to have thought of this and suggested it? Is this a candidate for Python 3000 yet? Chris
17
5634
by: MLH | last post by:
A97 Topic: If there is a way to preserve the values assigned to global variables when an untrapped runtime error occurs? I don't think there is, but I thought I'd ask. During development, I'm constantly running tests on imperfect code. On of the cumbersome jobs encountered is reassigning global vars their values after a close encounter with an untrapped runtime error. Rather than writing a procedure to simply reassign them all with a...
33
3052
by: MLH | last post by:
I've read some posts indicating that having tons of GV's in an Access app is a bad idea. Personally, I love GVs and I use them (possibly abuse them) all the time for everything imaginable - have been for years. If the machine has memory to spare and windows can use it - I'm thinking "Why not?" I was wondering what some of you have to say about that, particularly any severe "gotchas" you've had the unfortunate experience to contend with.
7
3146
by: Michael | last post by:
Hi newsgroup, as the subject indicates I am looking for an advice using global variables. I am not if this problem is more about style then C. If its wrong in thi group, sorry. So I have a couple of function that all need the same information (all located in the same file). By now it looks like /* file beginns */
8
2706
by: newbie | last post by:
Hello, I have questions about global variables in OOP (in general) and Python (in specific). I understand (I think) that global variables are generally not a good idea. However, if there are variables that need to be accessed by a number of classes that exists in separate namespaces (files), what would be the best way to do this? So far, I have approached the problem by making the variables attributes of one class and passing...
0
1443
by: Gary Herron | last post by:
Jacob Davis wrote: Yuck, YUCK, YUCK! You are breaking *so* many good-programming-practices, I hardly know where to start. First off: A python global is not what you think. There are *no* program wide globals. There are only module wide globals. Also, the "global isglobal" is absolutely meaningless as anything declared there is a (module level) global by definition.
6
1091
by: pistacchio | last post by:
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? thanks
4
2381
by: icarus | last post by:
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?
14
3675
by: Fred Block | last post by:
Hi All, I'm an experienced VB6 developer and now starting (newbee) with VB 2008 and I'm very excited. Here's an issue I'm experiencing right off the starting line and cannot make sense of it: I have a module (Public) and in it contains a few global variables (String data type). When I go to use these in a Form the value is "Nothing." Why is
0
9672
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
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
10436
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
10163
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
9040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
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
6780
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();...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3722
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.