Style/Structuring question: One vs. multiple global objects
Kirk McDonald
kirklin.mcdonald at gmail.com
Sun Jul 1 13:07:49 PDT 2007
Henning Hasemann wrote:
> I think the paranoia about globals comes from some experiences with or
> hints for other programming languages such as python etc... where
> globals are generally considered bad style, though I must confess I
> never understood why there is/was such a radical talking against them.
>
Globals are much less annoying in D than in Python. They are annoying in
Python because of Python's scoping rules. For the benefit of those who
don't know Python, the issue is this:
i = 12
def foo():
print i # prints '12'
i = 20
foo() # call foo
print i # prints 12; foo did not change 'i'
When it assigns 20 to 'i' inside of foo(), it is actually creating a new
name local to foo(), which shadows the global name. To assign to the
global name instead, you must use the 'global' keyword.
j = 14
def bar():
global j
print j # prints '14'
j = 40
bar()
print j # prints '40'; bar changed 'j'
You might expect this to lead to some confusion (particularly among
newbies to Python), and you'd be right. It is because of this
potentially confusing situation that globals are generally frowned upon
in Python.
In D, on the other hand, variables have to be explicitly declared. If
the only variable with a certain name is at global scope, then using
that name will obviously only refer to the global variable:
int i;
void foo() {
i = 12; // changes the global
}
D goes further by making the shadowing of global variables an error, and
making ambiguous situations in general errors. I am much less hesitant
to use globals in D than I am in Python.
--
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org
More information about the Digitalmars-d-learn
mailing list