private variables/methods

G

gabor

hi,

as far as i know in python there aren't any private (i mean not accessible
from the outside of the object) methods/fields.

why?

in java/c++ i can make a method private, this way unaccessible for the outside
world. i think it helps a lot to make for example a library more robust.

i know that there is some kind of notation to make a method/field private,
but one can still overwrite it's value.

what's the reason for this?

i'l mostly interested in the design reasons.

thanks,
gabor

--
That's life for you, said McDunn. Someone always waiting for someone
who never comes home. Always someone loving something more than that
thing loves them. And after awhile you want to destroy whatever
that thing is, so it can't hurt you no more.
-- R. Bradbury, "The Fog Horn"
 
D

Dave Benjamin

as far as i know in python there aren't any private (i mean not accessible
from the outside of the object) methods/fields.

why?

No offense, but this is like the 4000th time someone has asked that question
here. Could you try searching Google groups first?

Dave
 
G

gabor

No offense, but this is like the 4000th time someone has asked that question
here. Could you try searching Google groups first?

you're right, i'm sorry.

after reading the archives:

i think i didn't express myself too well.
i'll try again:

i'm aware of the fact that you can declare a variable private with "__".
but i just don't like prefix-notation. i don't like the mMember or
lpszCommandLine style notation, and also the $variable style ones.

at least for me it seemed that adding a "private" keyword somewhere is
more elegant. but there isn't anything like that.

that's why it seems to me that the designers of the language don't
recommend you to use private variables at all, but if you want, you can
use this 'hack' ( i mean the "__" notation).


thanks,
gabor
 
P

Peter Hansen

gabor said:
you're right, i'm sorry.

after reading the archives:

i think i didn't express myself too well.
i'll try again:

Don't bother. You perhaps didn't really read enough of the archives,
because Dave's point still stands. None of your questions or comments,
as far as I can tell, ask or say anything that hasn't already been
asked (and answered) or said before.

In summary: it's more of a philosophical difference than anything, and
Python simply doesn't *want* a "private" keyword, nor things like that
which artificially restrict the programmer. (Again, even that comment
adds nothing new, so you're really wasting your and our time by responding
rather than continuing to read the zillion old threads on the topic.)

-Peter
 
H

Harri Pesonen

Peter said:
Don't bother. You perhaps didn't really read enough of the archives,
because Dave's point still stands. None of your questions or comments,
as far as I can tell, ask or say anything that hasn't already been
asked (and answered) or said before.

Because it has been asked 4000 times probably means that there is a
great need for the feature...
In summary: it's more of a philosophical difference than anything, and
Python simply doesn't *want* a "private" keyword, nor things like that
which artificially restrict the programmer. (Again, even that comment
adds nothing new, so you're really wasting your and our time by responding
rather than continuing to read the zillion old threads on the topic.)

"Python" doesn't want a "private" keyword? I have quite a limited Python
experience but I would like to have the following features in Python
that are common in other languages:

* Option Explicit
* variable type declaration (optional)
* private variables/methods

Most of these are handy for large projects, where you want to be sure
that a class is not misused (by other developers). These also mean that
it is much harder to create bugs. I like Python a lot, but with these
features it would be much better for serious development of complex
applications, not just for scripting.

One thing I have noticed that the keyword "global" is very confusing.
For example, the following is syntactically valid Python:

a = 1
def b():
a = 2
def c():
return a

But it does not work as expected. Function b just creates a new local
variable "a" inside function b! The correct function is of course:

def b():
global a
a = 2

On the other hand, function c refers to the same global variable just
fine without any extra "global" keyword. Why on earth?? :) In every
other language I know you don't need "global". It is ugly.

Harri
 
A

Alex Martelli

Harri Pesonen wrote:
...
Because it has been asked 4000 times probably means that there is a
great need for the feature...

I can't think of ANY "feechur" from other popular languages that hasn't
been asked for, thousands of times. Does this mean that "there is a
great need" for each and all of them? Not at all: it just means that people
hanker for what they're familiar with. If Python were to satisfy even
1/10th of this incessant barrage of requests, it would devolve to a
large amorphous blob -- like many other languages have. The people
requesting these features are typically NOT experienced with Python:
they haven't experienced how the LACK of these features in fact makes
it easier and more productive to write application programs.

"Python" doesn't want a "private" keyword?

If Python can be said to have a will -- embodied in Guido or spread
as community consensus -- it definitely doesn't.
I have quite a limited Python
experience but I would like to have the following features in Python
that are common in other languages:

Not 'but', but rather, THEREFORE. Reread your words with this
change and with some luck you may get it.

* Option Explicit
* variable type declaration (optional)
* private variables/methods

Most of these are handy for large projects, where you want to be sure
that a class is not misused (by other developers). These also mean that
it is much harder to create bugs. I like Python a lot, but with these
features it would be much better for serious development of complex
applications, not just for scripting.

You are wrong. I used to harbor similar illusions (to a lesser degree,
because I _did_ have SOME experience with other dynamic languages,
but not in using them for really large apps) back when the language I
most used was C++. I was wrong, too.

Other developers aren't any likelier to "misuse" your class than you
are to misdesign it in the first place -- and you'll NEVER "be sure"
anyway, as restrictions can be worked around. _ADVISORY_
indications of "privacy" -- the convention of starting the name with
a single underscore -- are much simpler and equally effective for
your purposes. Python is wonderfully effective for programming
large applications, exactly as it is today.

One thing I have noticed that the keyword "global" is very confusing.

You are right. It would be better if the current module could be
imported -- by using some reserved special module name in a
perfectly ordinary 'import' instruction -- so that global variables
could then be re-bound as attributes of this module.

Just to give you an idea, in today's Python you could add this
feature as:

# part to be executed once, e.g. in site.py
import __builtin__, sys
_base_import = __builtin__.__import__
def __import__(name, *args):
if name == '__current_module__':
name = sys._getframe(1).f_globals['__name__']
return _base_import(name, *args)
__builtin__.__import__ = __import__
# end of part to be executed once

# example use
x = 23

def set_the_global():
import __current_module__
__current_module__.x = 45

print x
set_the_global()
print x


emits
23
45
For example, the following is syntactically valid Python:

a = 1
def b():
a = 2
def c():
return a

But it does not work as expected. Function b just creates a new local
variable "a" inside function b! The correct function is of course:

def b():
global a
a = 2

On the other hand, function c refers to the same global variable just
fine without any extra "global" keyword. Why on earth?? :) In every

Because reading is different from writing. Reading globals is (more or
less) all right; writing globals is a delicate decision that is well worth
emphasizing. So, anything that's written (any name that's re-bound,
to be precise) is deemed to be local -- unless explicitly mentioned in
a global statement.

The problem with global is that it's not clear enough. If there simply
was NO way at all to have any assignment to a bare name, such
as "a=2", EVER affect anything BUT a local, things would be much
clearer; the need to import __current_module__ would emphasize what
a serious, think-twice-about-it decision it is to choose to rebind
module-global names. It would also emphasize that 'global' means
'of this module', not in any way of ALL modules -- a misconception
that often affects newbies.

Hmmm -- maybe THIS is worth proposing for 2.4 (with a
pending deprecation warning for the global statement)...
other language I know you don't need "global". It is ugly.

Problem is, it's not quite ugly enough (nor quite clear enough).
Discouraging you from affecting globals is a swell idea, but I
think the 'global' statement may not be enough for that, whence
my newly conceived suggestion about importing...


Alex
 
S

Scott David Daniels

Alex said:
...
I can't think of ANY "feechur" from other popular languages that hasn't
been asked for, thousands of times....
Aha! caught the Martellibot in a rare memory failure (perhaps a rare
double-bit parity error)? To my knowledge, nobody has suggested the
autodeclaration of variables which begin with the letters 'I' through
'N' as integer variables. So there. :)

Now watch, he'll document 1003 requests on alt.lang.python.it.

-Scott David Daniels
(e-mail address removed)
 
J

Jordan Krushen

The problem with global is that it's not clear enough. If there simply
was NO way at all to have any assignment to a bare name, such
as "a=2", EVER affect anything BUT a local, things would be much
clearer; the need to import __current_module__ would emphasize what
a serious, think-twice-about-it decision it is to choose to rebind
module-global names. It would also emphasize that 'global' means
'of this module', not in any way of ALL modules -- a misconception
that often affects newbies.
Hmmm -- maybe THIS is worth proposing for 2.4 (with a
pending deprecation warning for the global statement)...

I'm rather amused at the thought of a module importing itself. I find it
cleaner than global, and it also emphasizes that modules are singletons,
if you think about how a module *can* import itself.

I think that __current_module__ is perhaps a bit too lengthy (although I
appreciate the motivation behind this), but aside from that, I like it.

I'm also pleased with the ouroboros-like imagery it conjures..

J.
 
D

Dennis Lee Bieber

Harri Pesonen fed this fish to the penguins on Friday 10 October 2003
12:16 pm:

Because it has been asked 4000 times probably means that there is a
great need for the feature...
Or it just means that there are 4000 undisciplined programmers out
there who can't trust their own coding and require the language to
protect them from themselves.

For them, I suggest coding in Ada...
"Python" doesn't want a "private" keyword? I have quite a limited
Python experience but I would like to have the following features in
Python that are common in other languages:

* Option Explicit

Only found in M$ Basic dialects as I recall. Real BASIC only required
declarations for arrays (needed the size), and used special suffix
characters for type identification.
* variable type declaration (optional)

Well, if you posit an option explicit statement, being required to
declare variables would become an option...
* private variables/methods

Why? You don't trust yourself to stay away from "internal" details
when using a class?

Let's see... Languages that don't require variable declarations:

BASIC (though it does allow suffix character to differentiate number
from string)
FORTRAN (though it uses variables beginning I-N as integers, all others
are real)
Python (no restriction, any variable can refer to any type of object)
REXX (no restriction that I know of)
DCL (and most command line scripting languages)
APL
LISP (at least, the versions up to the early 80s)
FORTH

Languages that require declarations for all variables:

Ada
COBOL
C++
Java
assembly (well, you have to declare the storage space at least)



--
 
D

Dennis Lee Bieber

Scott David Daniels fed this fish to the penguins on Friday 10 October
2003 17:09 pm:
Now watch, he'll document 1003 requests on alt.lang.python.it.
No... What he'll find are requests that variables beginning A-H and
O-Z be floats....

--
 
A

Alex Martelli

Scott said:
Aha! caught the Martellibot in a rare memory failure (perhaps a rare
double-bit parity error)? To my knowledge, nobody has suggested the
autodeclaration of variables which begin with the letters 'I' through
'N' as integer variables. So there. :)

Darn. I should have added a word -- a "current" or "currently" somewhere.
Arithmetic IF, variable types based on initial letter of the name, and
other such features are not in the _currently_ popular versions of Fortran
(and I'm sure we can find early-60, now-deplored feechurs of Cobol or
RPG that are also rarely or never asked for).

Now watch, he'll document 1003 requests on alt.lang.python.it.

that's it.comp.lang.python -- and I don't think I've met many old Fortran-IV
hands there...


Alex
 
N

Nick Vargish

Scott David Daniels said:
Aha! caught the Martellibot in a rare memory failure (perhaps a rare
double-bit parity error)? To my knowledge, nobody has suggested the
autodeclaration of variables which begin with the letters 'I' through
'N' as integer variables. So there. :)

I think two key phrases were "popular language" and "feature".

Nick
 
T

Terry Reedy

Jordan Krushen said:
I'm rather amused at the thought of a module importing itself. I find it
cleaner than global, and it also emphasizes that modules are singletons,
if you think about how a module *can* import itself.

You can already do this in the main module:
Traceback (most recent call last):
File said:
__name__ '__main__'
import __main__
__main__
a=3
__main__.__dict__['a'] 3
__main__.__dict__['b'] = 5
b
5
del __main__
__main__ NameError: name '__main__' is not defined
globals()[__name__] = __import__(__name__)
__main__
<module '__main__' (built-in)>

I believe globals line above will work in imported modules, in which
__name__ is import name (file name if from file), but have not tested
it in such.
I think that __current_module__ is perhaps a bit too lengthy

and redundant ;-)

Terry J. Reedy
 
A

Alex Martelli

Terry Reedy wrote:
...
globals()[__name__] = __import__(__name__)
__main__
<module '__main__' (built-in)>

I believe globals line above will work in imported modules, in which
__name__ is import name (file name if from file), but have not tested
it in such.

Yes, this will work at the global level in any module. But it's not a
normal import instruction, while the modified builtin __import__ I
showed does allow normal importing; and your _use_ of __import__ and
globals() cannot bind a _local_ variable of a function to the current
module object.

and redundant ;-)

I disagree. Lengthy it may be, but we do want a 'reserved module
name' to use for this purpose. For a normal import instruction to
work, and to work just as well if you cut and paste the same function
elsewhere, I think we want to define that "import somespecificname" is
importing THIS module, the CURRENT module, under that name (or another
specified with 'as'). This can be experimented with easily, by changing
the builtin __import__ (or setting an import hook, maybe) in site-specific
file; and if it catches on the builtin __import__ could easily be customized
to perform the same task quite speedily.


Alex
 
S

Sean Ross

Alex Martelli said:
I disagree. Lengthy it may be, but we do want a 'reserved module
name' to use for this purpose. For a normal import instruction to
work, and to work just as well if you cut and paste the same function
elsewhere, I think we want to define that "import somespecificname" is
importing THIS module, the CURRENT module, under that name (or another
specified with 'as'). This can be experimented with easily, by changing
the builtin __import__ (or setting an import hook, maybe) in site-specific
file; and if it catches on the builtin __import__ could easily be customized
to perform the same task quite speedily.

Hi.
I'm not sure I'm clear on what behaviour "import __current_module__" is
expected to have.
There's a bit more to follow but I'll ask my main question up front so we're
clear:

"Which of the following behaviours is preferred?"

I've been playing with some code, using my own pet global workaround, and
I'm not sure
if it's accomplishing the correct behaviour. The results are certainly not
the same as yours.
in fact, I think the behaviour of my version may be unexpected and dangerous
....

If inside module A you import a function f() from another module B that
tries to use the
current module directly, rather than global, to set variables and you call
that function
(i.e., B.f()), my version will affect the values of A's global variables
whereas yours does
not. For example, here is some output from a test run of each method. The
code for all
of this will be posted at the bottom of this message. Note: I've added some
print statements
to your code.


# Output of running setglobal1.py using import __current_module__
setglobal1.x = 23
ENTERING setglobal1.set_the_global()
global x = 23
set __current_module__.x = 45
global x = 45
EXITING setglobal1.set_the_global()
ENTERING setglobal2.set_the_global()
global x = 57
set __current_module__.x = 88
global x = 88
EXITING setglobal2.set_the_global()
setglobal1.x = 45


# Output of running main1.py using import __main__
main1.x = 23
ENTERING main1.foo()
global x = 23
set main.x = 45
global x = 45
EXITING main1.foo()
ENTERING main2.foo()
global x = 57
main2.x = 45
set main.x = 88
global x = 57
EXITING main2.foo()
main1.x = 88


As you can see, setglobal1.x = 45 in your version, but my analogous
variable main1.x = 88.

Here's the code:

#==============================================
# site.py
import __builtin__, sys
_base_import = __builtin__.__import__
def __import__(name, *args):
if name == '__current_module__':
name = sys._getframe(1).f_globals['__name__']
return _base_import(name, *args)
__builtin__.__import__ = __import__
# end of part to be executed once

#===============================================
# setglobal1.py

import setglobal2
x = 23

def set_the_global():
print "ENTERING setglobal1.set_the_global()"
import __current_module__
global x
print "global x = %s"%x
__current_module__.x = 45
print "set __current_module__.x = %s"%__current_module__.x
print "global x = %s"%x
print "EXITING setglobal1.set_the_global()"

if __name__ == "__main__":
print "setglobal1.x = %s"%x
set_the_global()
setglobal2.set_the_global()
print "setglobal1.x = %s"%x


#===============================================
# setglobal2.py
x = 57

def set_the_global():
print "ENTERING setglobal2.set_the_global()"
import __current_module__
global x
print "global x = %s"%x
__current_module__.x = 88
print "set __current_module__.x = %s"%__current_module__.x
print "global x = %s"%x
print "EXITING setglobal2.set_the_global()"

if __name__ == "__main__":
print "setglobal2.x = %s"%x
set_the_global()
print "setglobal2.x = %s"%x




# And now my version:

#===============================================
# main1.py
import main2

x = 23

def foo():
print "ENTERING main1.foo()"
import __main__ as main
global x
print "global x = %s"%main.x
main.x = 45
print "set main.x = %s"%main.x
print "global x = %s"%x
print "EXITING main1.foo()"

if __name__ == "__main__":
print "main1.x = %s"%x
foo()
main2.foo()
print "main1.x = %s"%x



#===============================================
# main2.py
x = 57

def foo():
print "ENTERING main2.foo()"
import __main__ as main
global x
print "global x = %s"%x
print "main2.x = %s"%main.x
main.x = 88
print "set main.x = %s"%main.x
print "global x = %s"%x
print "EXITING main2.foo()"

if __name__ == "__main__":
print "main2.x = %s"%x
foo()
print "main2.x = %s"%x



Thanks for your time,
Sean
 
T

Terry Reedy

Alex Martelli said:
Terry Reedy wrote:

I was slightly wrong since __name__ allows but does not constitute a
binding of the module itself.
I disagree. Lengthy it may be, but we do want a 'reserved module
name' to use for this purpose.

I believe it would be easily possible to bind a module to
<module>.__self__ or <module>. __module__ at the same time
<module>__name__, .__file__, and .__doc__ are. ('Current' is no more
needed for __module__ than for the other vars.) If their were use
cases for self-access nearly as good as those for the others, and not
just the cuteness factor, I would support the addition. I would guess
that Guido and the other main developers either have not had such
needs or have not recognized such needs. Don't know if this addition
has been discussed before, and don't have time to search right now.

Terry J. Reedy
 
D

Dennis Lee Bieber

Alex Martelli fed this fish to the penguins on Saturday 11 October 2003
08:46 am:
Darn. I should have added a word -- a "current" or "currently"
somewhere. Arithmetic IF, variable types based on initial letter of
the name, and other such features are not in the _currently_ popular

According to my text (FORTRAN 90/95 explained), the Arithmetic IF is
still available in Fortran 90, though considered "obsolescent" (a
phrase I would put on par with Python's "deprecated"). Implicit typing
(I-N -> integer) is also still in Fortran 90, though discouraged (but
one could say that of FORTRAN 77 too, and there is an awful lot of F77
code still being maintained (I should know, that's what I spent the
last 20 years doing!) by various defense contractors (and some was
developed new in the last decade even -- F90 had not made any in-roads
to the department I used to work for up to the time of my lay-off last
year).

Among the obsolescent features in F90: do loop with reals (removed in
F95), the above mentioned if, and the assigned goto (removed in F95 --
which would have required a major rewrite of one application I spent
years maintaining; it had been created as the /output/ from a
preprocessor that used a C-like syntax... local subroutines [with
global variables a la old BASIC] were handled by using assigned goto
for the return statements), alternate return labels, pause (removed in
F95), and Hollerith "H" edit descriptor (removed in F95).


--
 
A

Alex Martelli

Dennis said:
Alex Martelli fed this fish to the penguins on Saturday 11 October 2003
08:46 am:


According to my text (FORTRAN 90/95 explained), the Arithmetic IF
is
still available in Fortran 90, though considered "obsolescent" (a
phrase I would put on par with Python's "deprecated"). Implicit typing
(I-N -> integer) is also still in Fortran 90, though discouraged (but

i.e., they're there, but are not currently popular -- something popular
would be praised, not called names;-).


Alex
 
A

Alex Martelli

Terry Reedy wrote:
...
I believe it would be easily possible to bind a module to
<module>.__self__ or <module>. __module__ at the same time
<module>__name__, .__file__, and .__doc__ are. ('Current' is no more

Yes, it would (a tiny patch to the C code).
needed for __module__ than for the other vars.) If their were use
cases for self-access nearly as good as those for the others, and not
just the cuteness factor, I would support the addition. I would guess

My use case is: deprecating the global statement.


Alex
 
A

Alex Martelli

Sean Ross wrote:
...
Hi.
I'm not sure I'm clear on what behaviour "import __current_module__" is
expected to have.

Just like any other import, it binds the name to a module object -- except
that it specifically binds said name to the module containing the function
that executes this import statement. The use case is: deprecating the
global statement. Setting a global variable would instead use:
import __current_module__
__current_module__.thevariable = 23

So, your version does something very different from mine.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top