[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2018-09-19 Thread STINNER Victor


Change by STINNER Victor :


--
resolution:  -> out of date
stage:  -> resolved
status: open -> closed

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-09-05 Thread STINNER Victor

STINNER Victor added the comment:

My PR 780 doesn't support multiple Python interpreters in the same process. To 
support that, we need a more advanced solution. For example, add an hash table 
in the interpreter structure using the variable memory address as the key.

Maybe we can move step by step and start with the PR 780, and only later 
support multiple interpreters. PR 780 enhances the most common case, Python 
running a single interpreter.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-04-12 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

What if use the term "singleton"? It includes "initialize once" and "finalize 
at shutdown" meanings. _Py_INIT_SINGLETON() or _Py_SET_SINGLETON()?

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-04-12 Thread STINNER Victor

STINNER Victor added the comment:

I dislike _Py_SET_FINALIZED and _Py_SET_ONCE name.

I prefer to mention an "initialization" because it's a common pattern in 
programming and it is known that it only requires to be done once.

_PY_ONCEVAR_INIT() macro is unusual: it only evaluate the second parameter 
parameter, a C expression, if the variable is not initialized yet.

Py_SETREF() is different because it always evaluates its second argument, and 
in most cases, the second argument is an existing variable and not an 
expression.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-04-11 Thread Louie Lu

Changes by Louie Lu :


--
nosy: +louielu

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-04-10 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

Can you move forward this issue Victor? I'm very interesting in it. It is worth 
to advertise this API on Python-Dev.

_PyArg_Parser also can utilize this API.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-31 Thread Nick Coghlan

Nick Coghlan added the comment:

_PY_SET_FINALIZED is only one letter longer than _PY_ONCEVAR_INIT and the same 
length as the originally proposed _PY_STATICVAR_INIT.

Since it shouldn't be anywhere near as common as _Py_SETREF, I'm also okay in 
general with trading a bit of brevity for accuracy.

However, I don't want to trade away *too* much brevity, so I think we're going 
to have to choose between reminding readers of "this is finalized in 
Py_Finalize" or "this is a no-op if the target is already set", and leave the 
other aspect implicit.

In addition to the correctness argument above, my rationale for now favouring 
the former is that the logical leap in "this is finalized in Py_Finalize, so 
the assigned expression will only be executed once per Py_Initialize call" 
seems more reasonable to me than the one in "the assigned expression is only 
executed once per Py_Initialize call, so it will be finalized in Py_Finalize".

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-30 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

I agree with your rationale Nick, but _Py_SET_FINALIZED is a little too long 
and highlight only the second function of the macro. I don't have good name.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-30 Thread Nick Coghlan

Nick Coghlan added the comment:

I'm +1 for _Py_SET_FINALIZED with the semantics Serhiy suggests, and +0 for 
_Py_SET_ONCE.

My rationale for that preference is that _Py_SET_ONCE is a misnomer in the 
presence of

* multiple Py_Initialize/Py_Finalize cycles; and/or
* _Py_SETREF calls that replace the value to be finalized

 while _Py_SET_FINALIZED remains accurate in both cases.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-30 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

Ping. My suggestion is to rename _PY_ONCEVAR_INIT to _Py_SET_ONCE and make it 
returning the value. And apply this to more static and global variables.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-23 Thread Nick Coghlan

Nick Coghlan added the comment:

For module level variables, I'd expect this API to need to be used in tandem 
with switching the module over to PEP 489 multi-phase initialization.

By calling the new API in their _Py_mod_exec slot implementation, extension 
modules should be able to handle multiple initialize/finalize cycles correctly: 
https://www.python.org/dev/peps/pep-0489/#subinterpreters-and-interpreter-reloading

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-23 Thread Nick Coghlan

Nick Coghlan added the comment:

The main potential benefit I see to keeping the special variable declaration is 
that it may help avoid a certain category of error: calling _Py_ONCE_VAR_INIT 
on a stack local pointer reference (which would leave the global array with a 
reference to nonsense). While we don't care if the once_vars are static or not, 
we do care that they're not allocated on the call stack, as otherwise they 
won't be around for Py_Finalize() to clean up.

On the other hand, _Py_SET_ONCE is nice and easy to explain "it's similar to 
_Py_SETREF, but: 1) doesn't do anything if the reference is already set; and 2) 
registers the reference to be cleaned up in Py_Finalize"

Also interesting is the fact that you can still use _Py_SETREF to change a 
reference that was initialized with _Py_SET_ONCE without breaking anything. 
From that point of view, a better name might be _Py_SET_FINALIZED, emphasising 
the fact that it registers the pointer for finalization over the fact that it's 
a no-op when run on an already set pointer.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-23 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

Some code (_PyUnicode_FromId, bool_repr, create_filter) could be simpler if 
make _PY_ONCEVAR_INIT returning the value (NULL in case of error).

The signature of _PY_ONCEVAR_INIT() is the same as of _Py_SETREF(). If var == 
NULL both `_PY_ONCEVAR_INIT(var, expr)` and `_Py_SETREF(var, expr)` are 
equivalent to just `var = expr`. Maybe rename _PY_ONCEVAR_INIT to _Py_SET_ONCE?

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-23 Thread STINNER Victor

STINNER Victor added the comment:

I modified more modules to use the new API. I'm not sure that using the API in 
modules is safe.

It's safe to use the API in functions which begins with trying to initialize 
the variable. In such case, if the variable is cleared, calling the function 
later initialize again the variable and it's fine.

When for module variables only initialized when the module is initialized, 
there is a risk that a module function tries to access a variable which has 
been cleared previously during Python shutdown.

See for example changes in the _datetime module.

--

___
Python tracker 

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



[issue29881] Add a new private API clear private variables, which are initialized once, at Python shutdown

2017-03-23 Thread STINNER Victor

Changes by STINNER Victor <victor.stin...@gmail.com>:


--
title: Add a new private API for "static C variables" (_PyStaticVar) to clear 
them at exit -> Add a new private API clear private variables, which are 
initialized once, at Python shutdown

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



Private variables

2010-09-01 Thread Rasjid Wilcox
Hi all,

I am aware the private variables are generally done via convention
(leading underscore), but I came across a technique in Douglas
Crockford's book Javascript: The Good Parts for creating private
variables in Javascript, and I'd thought I'd see how it translated to
Python. Here is my attempt.

def get_config(_cache=[]):
private = {}
private['a'] = 1
private['b'] = 2
if not _cache:
class Config(object):
@property
def a(self):
return private['a']
@property
def b(self):
return private['b']
config = Config()
_cache.append(config)
else:
config = _cache[0]
return config

 c = get_config()
 c.a
1
 c.b
2
 c.a = 10
Traceback (most recent call last):
  File string, line 1, in fragment
AttributeError: can't set attribute
 dir(c)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
 d = get_config()
 d is c
True

I'm not really asking 'is it a good idea' but just 'does this work'?
It seems to work to me, and is certainly 'good enough' in the sense
that it should be impossible to accidentally change the variables of
c.

But is it possible to change the value of c.a or c.b with standard
python, without resorting to ctypes level manipulation?

Cheers,

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


Re: Private variables

2010-09-01 Thread Ryan Kelly
On Thu, 2010-09-02 at 11:10 +1000, Rasjid Wilcox wrote:
 Hi all,
 
 I am aware the private variables are generally done via convention
 (leading underscore), but I came across a technique in Douglas
 Crockford's book Javascript: The Good Parts for creating private
 variables in Javascript, and I'd thought I'd see how it translated to
 Python. Here is my attempt.
 
 def get_config(_cache=[]):
 private = {}
 private['a'] = 1
 private['b'] = 2
 if not _cache:
 class Config(object):
 @property
 def a(self):
 return private['a']
 @property
 def b(self):
 return private['b']
 config = Config()
 _cache.append(config)
 else:
 config = _cache[0]
 return config
 
  c = get_config()
  c.a
 1
  c.b
 2
  c.a = 10
 Traceback (most recent call last):
   File string, line 1, in fragment
 AttributeError: can't set attribute
  dir(c)
 ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
 '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
 '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
  d = get_config()
  d is c
 True
 
 I'm not really asking 'is it a good idea' but just 'does this work'?
 It seems to work to me, and is certainly 'good enough' in the sense
 that it should be impossible to accidentally change the variables of
 c.
 
 But is it possible to change the value of c.a or c.b with standard
 python, without resorting to ctypes level manipulation?

It's not easy, but it can be done by introspecting the property object
you created and munging the closed-over dictionary object:

c = get_config()
c.a
   1
c.__class__.__dict__['a'].fget.func_closure[0].cell_contents['a'] = 7
c.a
   7



  Cheers,

 Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au|  http://www.rfk.id.au/ramblings/gpg/ for details



signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Private variables

2010-09-01 Thread Ryan Kelly
On Thu, 2010-09-02 at 12:06 +1000, Ryan Kelly wrote:
 On Thu, 2010-09-02 at 11:10 +1000, Rasjid Wilcox wrote:
  Hi all,
  
  I am aware the private variables are generally done via convention
  (leading underscore), but I came across a technique in Douglas
  Crockford's book Javascript: The Good Parts for creating private
  variables in Javascript, and I'd thought I'd see how it translated to
  Python. Here is my attempt.
  
  def get_config(_cache=[]):
  private = {}
  private['a'] = 1
  private['b'] = 2
  if not _cache:
  class Config(object):
  @property
  def a(self):
  return private['a']
  @property
  def b(self):
  return private['b']
  config = Config()
  _cache.append(config)
  else:
  config = _cache[0]
  return config
  
   c = get_config()
   c.a
  1
   c.b
  2
   c.a = 10
  Traceback (most recent call last):
File string, line 1, in fragment
  AttributeError: can't set attribute
   dir(c)
  ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
  '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
  '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
  '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
   d = get_config()
   d is c
  True
  
  I'm not really asking 'is it a good idea' but just 'does this work'?
  It seems to work to me, and is certainly 'good enough' in the sense
  that it should be impossible to accidentally change the variables of
  c.
  
  But is it possible to change the value of c.a or c.b with standard
  python, without resorting to ctypes level manipulation?
 
 It's not easy, but it can be done by introspecting the property object
 you created and munging the closed-over dictionary object:
 
 c = get_config()
 c.a
1
 c.__class__.__dict__['a'].fget.func_closure[0].cell_contents['a'] = 7
 c.a
7
 


Heh, and of course I miss the even more obvious trick of just clobbering
the property with something else:

   c.a
  1
   setattr(c.__class__,a,7)
   c.a
  7
   


   Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au|  http://www.rfk.id.au/ramblings/gpg/ for details



signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Private variables

2010-09-01 Thread Rasjid Wilcox
On 2 September 2010 12:22, Ryan Kelly r...@rfk.id.au wrote:
 On Thu, 2010-09-02 at 12:06 +1000, Ryan Kelly wrote:
 On Thu, 2010-09-02 at 11:10 +1000, Rasjid Wilcox wrote:
  Hi all,
 
  I am aware the private variables are generally done via convention
  (leading underscore), but I came across a technique in Douglas
  Crockford's book Javascript: The Good Parts for creating private
  variables in Javascript, and I'd thought I'd see how it translated to
  Python. Here is my attempt.
 
  def get_config(_cache=[]):
      private = {}
      private['a'] = 1
      private['b'] = 2
      if not _cache:
          class Config(object):
              @property
              def a(self):
                  return private['a']
              @property
              def b(self):
                  return private['b']
          config = Config()
          _cache.append(config)
      else:
          config = _cache[0]
      return config
 
   c = get_config()
   c.a
  1
   c.b
  2
   c.a = 10
  Traceback (most recent call last):
    File string, line 1, in fragment
  AttributeError: can't set attribute
   dir(c)
  ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
  '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
  '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
  '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
   d = get_config()
   d is c
  True
 
  I'm not really asking 'is it a good idea' but just 'does this work'?
  It seems to work to me, and is certainly 'good enough' in the sense
  that it should be impossible to accidentally change the variables of
  c.
 
  But is it possible to change the value of c.a or c.b with standard
  python, without resorting to ctypes level manipulation?

 It's not easy, but it can be done by introspecting the property object
 you created and munging the closed-over dictionary object:

     c = get_config()
     c.a
    1
     c.__class__.__dict__['a'].fget.func_closure[0].cell_contents['a'] = 7
     c.a
    7

Ah!  That is what I was looking for.

 Heh, and of course I miss the even more obvious trick of just clobbering
 the property with something else:

   c.a
  1
   setattr(c.__class__,a,7)
   c.a
  7

Well, that is just cheating!  :-)

Anyway, thanks for that.  I still think it is 'good enough' for those
cases where private variables are 'required'.  In both cases one has
to go out of ones way to modify the attribute.  OTOH, I guess it
depends on what the use case is.  If it is for storing a secret
password that no other part of the system should have access to, then
perhaps not 'good enough' at all.

Cheers,

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


Re: Changing the private variables content

2009-07-23 Thread Ethan Furman

Ryniek90 wrote:


Got it:

exec('self.' + attr + '=\'' + val + '\'')

That worked. I think it'll do what you want now ;)

Ching-Yun Xavier Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: cont...@xavierho.com mailto:cont...@xavierho.com
Website: http://xavierho.com/



To bad, that didn't worked in my class. Still the same error:

  mod.print_module('socket')

Traceback (most recent call last):
 File pyshell#121, line 1, in module
   mod.print_module('socket')
 File pyshell#118, line 51, in print_module
   module_open = open(self._this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''
 


:-/


What is the point of the _SetVar method?

Instead of:

self._SetVar(self._this_module, os.path.join(root, f))

just do:

self._this_module = os.path.join(root, f)

(unless I'm misunderstanding what you're trying to do!)



Of course i;ve tried, but still get the same error:


  mod.print_module('socket')

Traceback (most recent call last):
 File pyshell#121, line 1, in module
   mod.print_module('socket')
 File pyshell#118, line 51, in print_module
   module_open = open(self.this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''
 


It looks like private variable have specific naure, that prevent from 
traditional editing them.

Still searching for some tuts about private methods and variables.


No.  There is nothing special about variables with a leading underscore.

_number

is treated by Python *exactly* the same as

number

.  The specific problem in your code above is your _SetVar function, 
among the more general problem of not yet having a good understanding of 
classes in Python.  Keep studying, Python is an awesome language.


I was able to make this work -- hope it helps.

8---
import os
import sys

class ModPrint(object):
uThis will be the doc.
def __init__(self):
self._default_search_path = sys.exec_prefix

def _search_for_module(self, chosen_module, search_path):
for root, dirs, files in os.walk(search_path):
for f in files:
if f == (%s.py % chosen_module):
return os.path.join(root, f)

def print_module(self, chosen_module, user_search_path=''):
search_path = user_search_path or self._default_search_path
module = self._search_for_module(chosen_module, search_path)
if module is not None:
module_open = open(module, 'rb')
module_text = module_open.read()
module_open.close()
return module_text
return 'Module not found...'
8---
--
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the private variables content

2009-07-23 Thread Ethan Furman
Or, in other words, what Steven D'Aprano had already said.  Guess I 
should read the whole thread before madly posting!  :)


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


Re: Re: Changing the private variables content

2009-07-22 Thread Ryniek90




Temat:
Re: Changing the private variables content
Od:
Gary Herron gher...@islandtraining.com
Data:
Tue, 21 Jul 2009 14:14:44 -0700
Do:
Ryniek90 rynie...@gmail.com

Do:
Ryniek90 rynie...@gmail.com
Kopia:
python-list@python.org


Ryniek90 wrote:

Hi.
I'm writing some class, and decided to use inside private method and 
some private variables. While with method i haven't got any problem's 
with variables i have.

Maybe some example.
A class with private method and private variable:


 class Secret(object):
   #
   def __init__(self):
   self._number = 1
   #
   def _secret(self):
   print self._number
   def showit(self):
   print Secret number is:\n
   self._secret()

 sec = Secret()
 sec.showit()
Secret number is:

1
 sec._number
1
 sec._number = 2
 sec._number
2
 sec._number += 3
 sec._number
5



As You can see, i made class with private method and private variable 
inside __init__ constructor. I've changed also the variable value, 
but outside class.
I've got problem with changing some variable value _inside__my_ 
class, which i'm writing.


Not sure this is what you are asking, but a method (which is how I 
interpret _inside__my_ class) changes the value by normal assignment 
like this:


class Secret(object):
 ...
 def SetNumber(self,value):
   self._number = value

Is that what you were asking?


Gary Herron



I've searched over google, some tuts with topics about operations on 
private variables, but didn't found anything - only how to make them, 
but no how to assign new objects/override them with new content (and 
other advanced and helpful options).


If someone could help me, it would be great.

Thanks.






Thanks for hint, but looks like i can't do what i want.

Maybe i show You my class:



class ModPrint(object):
  
   u

   This will be the doc.
   
  
   def __init__(self):
  
   #Assign the Python installation directory - sys.exec_prefix - to 
variable

   self._default_search_path=sys.exec_prefix
   self._chosen_module = ''
   self._user_search_path = ''
   self._this_module = ''
  
   def _SetVar(self, attr, val):
   self.attr = val   
  
   def _search_for_module(self, *args):
  
   Private method which walks through default Python 
installation directories, and search for prefered module.
  
   #walking thru all directories available in path '_user_search_path'

   for root, dirs, files in os.walk(self._user_search_path):
   for f in files:
  
   #if found file 'f' is THAT module,

   #full path to THAT file is assigned to variable
   if f == (%s.py % self._chosen_module):
   self._SetVar(self._this_module, os.path.join(root, f))
  
  
   def print_module(self, _chosen_module='', _user_search_path='', 
_default_search_path=sys.exec_prefix,):
  
   Reads module chosen by user, and returns full content of this 
module, as it is.
  
  
   #if custom search path hasn't been assigned,

   #default path is being assigned as custom path
   if self._user_search_path == '':
   self._user_search_path = self._default_search_path
  
   #using private method '_search_for_module' with 'self.' preffix

   #to search for prefered module
   self._search_for_module(_chosen_module, _user_search_path)
  
   #opening prefered module with read-only binary mode

   #and assigning it to 'module_open' variable
   module_open = open(self._this_module, 'rb')
  
   #reading this file and assigning it to variable

   module_text = module_open.read()
  
   #closing read file; the read content is still available

   #it's stored in variable 'module_text'
   module_open.close()
  
   #returning the read content

   return module_text



When i use this class in Python IDLE, i've got this error:

 mod = ModPrint()
 import socket
 mod.print_module('socket')

Traceback (most recent call last):
 File pyshell#60, line 1, in module
   mod.print_module('socket')
 File pyshell#57, line 48, in print_module
   module_open = open(self._this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''



As You can see, i can't assign the new value os.path.join(root, f) to 
the 'self._this_module variable'.

So for sure i've made some mistake in method:


def _SetVar(self, attr, val):
   self.attr = val   

When i've changed private variables to normal, stored in class (in 
__init__ method), it was the same situation - i couldn't change this 
variable value.



 mod = ModPrint()
 mod.print_module('os')

Traceback (most recent call last):
 File pyshell#72, line 1, in module
   mod.print_module('os')
 File pyshell#64, line 48, in print_module
   module_open = open(self.this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''



Thanks i someone could

Re: Re: Changing the private variables content

2009-07-22 Thread Xavier Ho
On Wed, Jul 22, 2009 at 10:29 PM, Ryniek90 rynie...@gmail.com wrote:

 Thanks for hint, but looks like i can't do what i want.


That's because


 def _SetVar(self, attr, val):
   self.attr = val


 doesn't work as you might think. However, I tried to replace it with:

val('self.' + attr + '=\'' + val + '\'')

and it gives me a syntax error!

  File test.py, line 7, in _setVar
eval('self.' + attr + '=\'' + val + '\'')
  File string, line 1
self.var='Mrra'
^
SyntaxError: invalid syntax

So, uh, I'm wondering if this is a bug. And also the solution to his
problem.

Good luck. Any ideas appreciated.

Ching-Yun Xavier Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: cont...@xavierho.com
Website: http://xavierho.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Changing the private variables content

2009-07-22 Thread Xavier Ho

 val('self.' + attr + '=\'' + val + '\'')


Obviously that was eval, not val. Also it doesn't work without the escaped
single quotes, either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Changing the private variables content

2009-07-22 Thread Xavier Ho
Got it:

exec('self.' + attr + '=\'' + val + '\'')

That worked. I think it'll do what you want now ;)

Ching-Yun Xavier Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: cont...@xavierho.com
Website: http://xavierho.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the private variables content

2009-07-22 Thread MRAB

Ryniek90 wrote:




Temat:
Re: Changing the private variables content
Od:
Gary Herron gher...@islandtraining.com
Data:
Tue, 21 Jul 2009 14:14:44 -0700
Do:
Ryniek90 rynie...@gmail.com

Do:
Ryniek90 rynie...@gmail.com
Kopia:
python-list@python.org


Ryniek90 wrote:

Hi.
I'm writing some class, and decided to use inside private method and 
some private variables. While with method i haven't got any problem's 
with variables i have.

Maybe some example.
A class with private method and private variable:


 class Secret(object):
   #
   def __init__(self):
   self._number = 1
   #
   def _secret(self):
   print self._number
   def showit(self):
   print Secret number is:\n
   self._secret()

 sec = Secret()
 sec.showit()
Secret number is:

1
 sec._number
1
 sec._number = 2
 sec._number
2
 sec._number += 3
 sec._number
5



As You can see, i made class with private method and private variable 
inside __init__ constructor. I've changed also the variable value, 
but outside class.
I've got problem with changing some variable value _inside__my_ 
class, which i'm writing.


Not sure this is what you are asking, but a method (which is how I 
interpret _inside__my_ class) changes the value by normal assignment 
like this:


class Secret(object):
 ...
 def SetNumber(self,value):
   self._number = value

Is that what you were asking?


Gary Herron



I've searched over google, some tuts with topics about operations on 
private variables, but didn't found anything - only how to make them, 
but no how to assign new objects/override them with new content (and 
other advanced and helpful options).


If someone could help me, it would be great.

Thanks.






Thanks for hint, but looks like i can't do what i want.

Maybe i show You my class:



class ModPrint(object):
 u
   This will be the doc.
   
 def __init__(self):
 #Assign the Python installation directory - sys.exec_prefix 
- to variable

   self._default_search_path=sys.exec_prefix
   self._chosen_module = ''
   self._user_search_path = ''
   self._this_module = ''
 def _SetVar(self, attr, val):
   self.attr = valdef _search_for_module(self, *args):
 Private method which walks through default Python 
installation directories, and search for prefered module.
 #walking thru all directories available in path 
'_user_search_path'

   for root, dirs, files in os.walk(self._user_search_path):
   for f in files:
 #if found file 'f' is THAT module,
   #full path to THAT file is assigned to variable
   if f == (%s.py % self._chosen_module):
   self._SetVar(self._this_module, os.path.join(root, f))
   def print_module(self, 
_chosen_module='', _user_search_path='', 
_default_search_path=sys.exec_prefix,):
 Reads module chosen by user, and returns full content of 
this module, as it is.

   #if custom search path hasn't been assigned,
   #default path is being assigned as custom path
   if self._user_search_path == '':
   self._user_search_path = self._default_search_path
 #using private method '_search_for_module' with 'self.' 
preffix

   #to search for prefered module
   self._search_for_module(_chosen_module, _user_search_path)
 #opening prefered module with read-only binary mode
   #and assigning it to 'module_open' variable
   module_open = open(self._this_module, 'rb')
 #reading this file and assigning it to variable
   module_text = module_open.read()
 #closing read file; the read content is still available
   #it's stored in variable 'module_text'
   module_open.close()
 #returning the read content
   return module_text



When i use this class in Python IDLE, i've got this error:

  mod = ModPrint()
  import socket
  mod.print_module('socket')

Traceback (most recent call last):
 File pyshell#60, line 1, in module
   mod.print_module('socket')
 File pyshell#57, line 48, in print_module
   module_open = open(self._this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''
 


As You can see, i can't assign the new value os.path.join(root, f) to 
the 'self._this_module variable'.

So for sure i've made some mistake in method:


def _SetVar(self, attr, val):
   self.attr = val   
When i've changed private variables to normal, stored in class (in 
__init__ method), it was the same situation - i couldn't change this 
variable value.



  mod = ModPrint()
  mod.print_module('os')

Traceback (most recent call last):
 File pyshell#72, line 1, in module
   mod.print_module('os')
 File pyshell#64, line 48, in print_module
   module_open = open(self.this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''
 


Thanks i someone could

Re: Changing the private variables content

2009-07-22 Thread Xavier Ho
 What is the point of the _SetVar method?


So you can set any variable in that class, I guess?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the private variables content

2009-07-22 Thread Steven D'Aprano
On Wed, 22 Jul 2009 14:29:20 +0200, Ryniek90 wrote:

 When i use this class in Python IDLE, i've got this error: 
...
 Traceback (most recent call last):
   File pyshell#60, line 1, in module
 mod.print_module('socket')
   File pyshell#57, line 48, in print_module
 module_open = open(self._this_module, 'rb')
 IOError: [Errno 2] No such file or directory: ''
  
 
 
 As You can see, i can't assign the new value os.path.join(root, f) to
 the 'self._this_module variable'.

In the __init__ method, you successfully set the `_this_module` attribute:

self._this_module = ''

That works, so it proves that you *can* set a private attribute.

Later on, you call the `_SetVar` method, which does this:

def _SetVar(self, attr, val):
self.attr = val   

In English, this method does this:

(1) Take two arguments, and store them in variables called attr and 
val.

(2) Assign the value stored in val to an attribute named exactly attr.

What you actually want is:

(1) Take two arguments, and store them in variables called attr and 
val.

(2) Assign the value stored in val to an attribute with the name stored 
in the variable attr.

Can you see the difference?

What you actually want is:

def _SetVar(self, attr, val):
setattr(self, attr, val)


Your code is terribly complicated. This will probably do what you want. 
(Warning -- I haven't tested it, so there may be a few errors.)


class ModPrint(object):
u
This will be the doc.

def __init__(self, default_search_path=''):
self.default_search_path = ''

   def find_module(self, modulename, search_path=''):
   if search_path == '':
   # Try the default search path instead.
   search_path = self.default_search_path
if search_path == '':  # still blank.
# Try the Python search path instead.
   search_path = sys.exec_prefix
for root, dirs, files in os.walk(search_path):
for f in files:
if f == %s.py % modulename:
return os.path.join(root, f)

def get_module_text(self, modulename, search_path=''):
filename = self.find_module(modulename, search_path)
module_open = open(filename, 'rb')
module_text = module_open.read()
module_open.close()
return module_text


I changed the name of print_module_text because it doesn't actually print 
anything.



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


Re: Changing the private variables content

2009-07-22 Thread Ryniek90


Got it:

exec('self.' + attr + '=\'' + val + '\'')

That worked. I think it'll do what you want now ;)

Ching-Yun Xavier Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: cont...@xavierho.com mailto:cont...@xavierho.com
Website: http://xavierho.com/


To bad, that didn't worked in my class. Still the same error:

 mod.print_module('socket')

Traceback (most recent call last):
 File pyshell#121, line 1, in module
   mod.print_module('socket')
 File pyshell#118, line 51, in print_module
   module_open = open(self._this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''



:-/

What is the point of the _SetVar method?

Instead of:

self._SetVar(self._this_module, os.path.join(root, f))

just do:

self._this_module = os.path.join(root, f)

(unless I'm misunderstanding what you're trying to do!)



Of course i;ve tried, but still get the same error:


 mod.print_module('socket')

Traceback (most recent call last):
 File pyshell#121, line 1, in module
   mod.print_module('socket')
 File pyshell#118, line 51, in print_module
   module_open = open(self.this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''



It looks like private variable have specific naure, that prevent from 
traditional editing them.

Still searching for some tuts about private methods and variables.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the private variables content

2009-07-22 Thread Dave Angel

Ryniek90 wrote:

snip


It looks like private variable have specific naure, that prevent from 
traditional editing them.

Still searching for some tuts about private methods and variables.



There's no tutorial on private variables for good reason:

Private variables have no special characteristics.  The compiler and 
runtime library don't treat them specially (except for the highly 
controversial from xx import *).  It's strictly a programming 
convention.  You've got some other bugs in your code, which I can't help 
you with because your code comes across formatted so strangely that it 
cannot compile here.  Some things you might do to make it easier to get 
help:


1) make sure you're not mixing tabs and spaces in your source code
2) post using text messages, so they don't get reformatted.
3) copy/paste the code and error messages into your message, don't retype.
4) whenever you've made more than trivial changes to the code, repost it 
all, since it's very difficult to tell which suggestions you've 
followed, and which ones you haven't gotten yet, or maybe dismissed 
because they didn't work.


DaveA

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


Re: Changing the private variables content

2009-07-22 Thread Jean-Michel Pichavant

Steven D'Aprano wrote:

On Wed, 22 Jul 2009 14:29:20 +0200, Ryniek90 wrote:

  

When i use this class in Python IDLE, i've got this error: 


...
  

Traceback (most recent call last):
  File pyshell#60, line 1, in module
mod.print_module('socket')
  File pyshell#57, line 48, in print_module
module_open = open(self._this_module, 'rb')
IOError: [Errno 2] No such file or directory: ''
 


As You can see, i can't assign the new value os.path.join(root, f) to
the 'self._this_module variable'.



In the __init__ method, you successfully set the `_this_module` attribute:

self._this_module = ''

That works, so it proves that you *can* set a private attribute.

Later on, you call the `_SetVar` method, which does this:

def _SetVar(self, attr, val):
self.attr = val   


In English, this method does this:

(1) Take two arguments, and store them in variables called attr and 
val.


(2) Assign the value stored in val to an attribute named exactly attr.

What you actually want is:

(1) Take two arguments, and store them in variables called attr and 
val.


(2) Assign the value stored in val to an attribute with the name stored 
in the variable attr.


Can you see the difference?

What you actually want is:

def _SetVar(self, attr, val):
setattr(self, attr, val)


Your code is terribly complicated. This will probably do what you want. 
(Warning -- I haven't tested it, so there may be a few errors.)



class ModPrint(object):
u
This will be the doc.

def __init__(self, default_search_path=''):
self.default_search_path = ''

   def find_module(self, modulename, search_path=''):
   if search_path == '':
   # Try the default search path instead.
   search_path = self.default_search_path
if search_path == '':  # still blank.
# Try the Python search path instead.
   search_path = sys.exec_prefix
for root, dirs, files in os.walk(search_path):
for f in files:
if f == %s.py % modulename:
return os.path.join(root, f)

def get_module_text(self, modulename, search_path=''):
filename = self.find_module(modulename, search_path)
module_open = open(filename, 'rb')
module_text = module_open.read()
module_open.close()
return module_text


I changed the name of print_module_text because it doesn't actually print 
anything.




  
Moreover, if I'm not wrong there is absolutely no difference in the way 
python is handling private and public attributes, for python, both are 
the same kind of attributes. This is purely conventional (some doc 
processing tool will take into account the private prefix).


So there is absolutely no restriction in writing self._myVar = 0 in any 
of the instance methods.


JM

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


Re: Changing the private variables content

2009-07-22 Thread Piet van Oostrum
 Ryniek90 rynie...@gmail.com (R) wrote:

R It looks like private variable have specific naure, that prevent from
R traditional editing them.
R Still searching for some tuts about private methods and variables.

Why do you stubbornly keep saying that, while you have been told that it
is not the case. Instead you would do better debugging your own case
instead of making false claims. Sprinkle a few print statements in your
code to see what is happening.

Here are a few thing for you to look at:

   #using private method '_search_for_module' with 'self.' prefix
   #to search for prefered module
   self._search_for_module(_chosen_module, _user_search_path)

You call it with 2 parameters: _chosen_module, _user_search_path
Look at the definition:

   def _search_for_module(self, *args):

It has *args to pick up the arguments, but they are not used in the
body. Instead you use self._user_search_path and self._chosen_module.
The latter one is always '', never changed to anything else. So it is
not surprising that the module is not found.
 
In print_module you have the same kind of confusion.

Do you think that magically self._chosen_module gets the value of
_chosen_module? Is that you idea of `private variables'?

Or do you think that *args does magical things?

   Private method which walks through default Python
   installation directories, and search for prefered module.
   #walking thru all directories available in path _user_search_path'
   for root, dirs, files in os.walk(self._user_search_path):
   for f in files:
   #if found file 'f' is THAT module,
   #full path to THAT file is assigned to variable
   print Trying %s % f
   if f == (%s.py % self._chosen_module):
   self._this_module = os.path.join(root, f)


-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Changing the private variables content

2009-07-21 Thread Ryniek90

Hi.
I'm writing some class, and decided to use inside private method and 
some private variables. While with method i haven't got any problem's 
with variables i have.

Maybe some example.
A class with private method and private variable:


 class Secret(object):
   #
   def __init__(self):
   self._number = 1
   #
   def _secret(self):
   print self._number
   def showit(self):
   print Secret number is:\n
   self._secret()

 sec = Secret()
 sec.showit()
Secret number is:

1
 sec._number
1
 sec._number = 2
 sec._number
2
 sec._number += 3
 sec._number
5



As You can see, i made class with private method and private variable 
inside __init__ constructor. I've changed also the variable value, but 
outside class.
I've got problem with changing some variable value _inside__my_ class, 
which i'm writing.
I've searched over google, some tuts with topics about operations on 
private variables, but didn't found anything - only how to make them, 
but no how to assign new objects/override them with new content (and 
other advanced and helpful options).


If someone could help me, it would be great.

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


Re: Changing the private variables content

2009-07-21 Thread Gary Herron

Ryniek90 wrote:

Hi.
I'm writing some class, and decided to use inside private method and 
some private variables. While with method i haven't got any problem's 
with variables i have.

Maybe some example.
A class with private method and private variable:


 class Secret(object):
   #
   def __init__(self):
   self._number = 1
   #
   def _secret(self):
   print self._number
   def showit(self):
   print Secret number is:\n
   self._secret()

 sec = Secret()
 sec.showit()
Secret number is:

1
 sec._number
1
 sec._number = 2
 sec._number
2
 sec._number += 3
 sec._number
5



As You can see, i made class with private method and private variable 
inside __init__ constructor. I've changed also the variable value, but 
outside class.
I've got problem with changing some variable value _inside__my_ class, 
which i'm writing.


Not sure this is what you are asking, but a method (which is how I 
interpret _inside__my_ class) changes the value by normal assignment 
like this:


class Secret(object):
 ...
 def SetNumber(self,value):
   self._number = value

Is that what you were asking?


Gary Herron



I've searched over google, some tuts with topics about operations on 
private variables, but didn't found anything - only how to make them, 
but no how to assign new objects/override them with new content (and 
other advanced and helpful options).


If someone could help me, it would be great.

Thanks.


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


Re: Changing the private variables content

2009-07-21 Thread David Stanek
On Tue, Jul 21, 2009 at 6:00 PM, Rhodri
Jamesrho...@wildebst.demon.co.uk wrote:
 On Tue, 21 Jul 2009 21:55:18 +0100, Ryniek90 rynie...@gmail.com wrote:

 Hi.
 I'm writing some class, and decided to use inside private method and some
 private variables. While with method i haven't got any problem's with
 variables i have.

 There is no mechanism in Python that makes attributes truly private.
 self._number is an attribute just like any other, the whole business
 with _leading_underscores is purely a matter of convention.  If you
 have an instance attribute or method with a leading underscore, you
 know that using it or calling it isn't something you're supposed
 to do outside its class, but nothing will stop you doing exactly that
 if you're rude enough to try.


Doubling the _ will give you a little more privacy. It really just
mangles the attribute name, but it close to what you want.

I just use a _single_under to tell other programmers that they
shouldn't be accessing that attribute directly. To my knowledge
nothing bad has happened because things are public and using the
__double_under makes testing a little harder.

   class C(object):
  ... def __init__(self):
  ... self.__x = 0
  ...
   c = C()
   c.__x
  Traceback (most recent call last):
File stdin, line 1, in module
  AttributeError: 'C' object has no attribute '__x'
   c._C__x
  0


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: private variables

2007-01-09 Thread Bruno Desthuilliers
belinda thom a écrit :
 Hello,
 
 In what version of python were private variables added?

Which private variables ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: private variables

2007-01-09 Thread belinda thom

On Jan 9, 2007, at 12:20 AM, Bruno Desthuilliers wrote:

 belinda thom a écrit :
 Hello,

 In what version of python were private variables added?

 Which private variables ?

Haha.

The ones that are provided for convenience (via name mangling) that  
aren't really private if you wish to violate convention.

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


Re: private variables

2007-01-09 Thread Gabriel Genellina

At Tuesday 9/1/2007 04:38, belinda thom wrote:


I knew it was a beehive, but I had hoped someone would know which
version they were released, so I can put the proper statement into my
tutorial (e.g. In version foo, Python provided some support for
private variables...). I've been avoiding getting stung b/c I see
both sides and have no preference for one vs. the other.


1.5, but I doubt anyone is still using a version earlier than 1.52 anymore.


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

private variables

2007-01-08 Thread belinda thom
Hello,

In what version of python were private variables added?

Thanks,

--b

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


Re: private variables

2007-01-08 Thread Thomas Ploch
belinda thom schrieb:
 Hello,
 
 In what version of python were private variables added?
 
 Thanks,
 
 --b
 

With this question you stepped into a bee hive. :-)

Read the 'Why less emphasis on private data?' thread.

But I can't tell you, when this so called 'private variables' were added.

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


Re: private variables

2007-01-08 Thread Ravi Teja

belinda thom wrote:
 Hello,

 In what version of python were private variables added?

 Thanks,

 --b

Short answer - 1.5 (or - so long ago that it doesn't matter anymore)
Long answer - There are no true private variables in Python. Just
private variables names by convention.

See Python docs for a detailed explanation.

Ravi Teja.

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


Re: private variables

2007-01-08 Thread belinda thom
I knew it was a beehive, but I had hoped someone would know which  
version they were released, so I can put the proper statement into my  
tutorial (e.g. In version foo, Python provided some support for  
private variables...). I've been avoiding getting stung b/c I see  
both sides and have no preference for one vs. the other.

--b

On Jan 8, 2007, at 10:11 PM, Thomas Ploch wrote:

 belinda thom schrieb:
 Hello,

 In what version of python were private variables added?

 Thanks,

 --b


 With this question you stepped into a bee hive. :-)

 Read the 'Why less emphasis on private data?' thread.

 But I can't tell you, when this so called 'private variables' were  
 added.

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

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


Re: private variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-25 Thread Simon Brunning
On Mon, 24 Jan 2005 12:17:13 -0600, Philippe C. Martin
[EMAIL PROTECTED] wrote:
 
 I use __for private variables because I must have read on net it was
 the way to do so - yet this seems to have changed - thanks:
 
 http://www.network-theory.co.uk/docs/pytut/tut_77.html

Nope, that's still the right way to make a member 'really' private.
Stephen was pointing out a very common Python idiom - private by
convention, and suggesting that using it would be more appropriate.

A member with a single preceding underscore is private by convention.
That is to say, there is no mechanism in place to prevent clients of
the class accessing these members, but they should consider themselves
to have been warned that they do so at their own risk.

If you take the back off the radio, the warranty is void. ;-)

I (and by inference Stephen) feel that this is a more Pythonic
approach. Give the programmer the information that they need, but
don't try to stop them from doing what they need to do.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: private variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-25 Thread michele . simionato
Name mangling is there to keep you from accidentally hiding such an
attribute in a subclass, but how often is this really a danger? Can
someone give me an example of where __-mangling really solved a
problem
for them, where a simple leading underscore wouldn't have solved the
same problem?

Look at the autosuper implementation on Guido's descrintro paper;
there the
fact that you user __super instead of _super is essential.

However I have written tens of thousands of lines of Python code and
never
needed __protected variables except in a few experimental scripts for
learning purpose. So I agree that the need does not occur often, but it
is still an useful thing to have.
Michele Simionato

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


Re: private variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-25 Thread Philippe C. Martin
Well I _was_ a bit slow on that one !

So I will happily stick to the double underscore.

Regards,

Philippe



Le mardi 25 janvier 2005  10:28 +, Simon Brunning a crit :
 On Mon, 24 Jan 2005 12:17:13 -0600, Philippe C. Martin
 [EMAIL PROTECTED] wrote:
  
  I use __for private variables because I must have read on net it was
  the way to do so - yet this seems to have changed - thanks:
  
  http://www.network-theory.co.uk/docs/pytut/tut_77.html
 
 Nope, that's still the right way to make a member 'really' private.
 Stephen was pointing out a very common Python idiom - private by
 convention, and suggesting that using it would be more appropriate.
 
 A member with a single preceding underscore is private by convention.
 That is to say, there is no mechanism in place to prevent clients of
 the class accessing these members, but they should consider themselves
 to have been warned that they do so at their own risk.
 
 If you take the back off the radio, the warranty is void. ;-)
 
 I (and by inference Stephen) feel that this is a more Pythonic
 approach. Give the programmer the information that they need, but
 don't try to stop them from doing what they need to do.
 
-- 
***
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
***

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


Re: private variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-25 Thread Richie Hindle

[Toby]
 The problem occured because the double-underscore mangling uses the class 
 name, but ignores module names. A related project already had a class named C 
 derived from B  (same name - different module).

Yikes!  A pretty bizarre case, but nasty when it hits.  I guess the
double-underscore system can give you a false sense of security.

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: private variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-25 Thread Steven Bethard
Toby Dickenson wrote:
I have a counterexample. Consider refactoring a class from
class B(A):
etc
into
class C(A):
etc
class B(C):
etc
Usage of some double-undescore attributes moved from B to the new intermediate 
base class C. Unit tests on B still passed, so that change is safe. right?

The problem occured because the double-underscore mangling uses the class 
name, but ignores module names. A related project already had a class named C 
derived from B  (same name - different module). My refactoring caused 
aliasing of some originally distinct double-underscore attributes.
Very interesting.  I hadn't ever really thought about it, but I guess 
this shows that even __-mangling won't solve all of the 
attribute-renaming problems...

A somewhat related problem is briefly discussed in Guido's autosuper 
example:
http://www.python.org/2.2.3/descrintro.html#metaclass_examples
where a base class derived from a class using autosuper but with the 
same name as the superclass might get the wrong self.__super.

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


private variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-24 Thread Steven Bethard
Philippe C. Martin wrote:
 class Debug_Stderr:
   __m_text = ''
   __m_log_text = None
   __m_dbg = None
   __m_refresh_count = 0
rant
I don't see the benefit in 99.9% of cases for making class variables 
like this private.  If you don't want people to use them, simply use 
the standard convention[1] for non-public variables:

class Debug_Stderr:
_text = ''
_log_text = None
_dbg = None
_refresh_count = 0
A lot of the time, it actually makes sense to make (at least some of) 
the attributes public, e.g.:

class Debug_Stderr:
text = ''
log_text = None
dbg = None
refresh_count = 0
I don't know what all the variables in this specific example are 
intended to be, but it certainly seems like something like 
'refresh_count' might be useful to clients of the class.

Name mangling is there to keep you from accidentally hiding such an 
attribute in a subclass, but how often is this really a danger?  Can 
someone give me an example of where __-mangling really solved a problem 
for them, where a simple leading underscore wouldn't have solved the 
same problem?

/rant
Steve
[1] http://www.python.org/peps/pep-0008.html
--
http://mail.python.org/mailman/listinfo/python-list


RE: Why I use private variables (WAS: RE:private variables a.k.a. name mangling?)

2005-01-24 Thread Philippe C. Martin
The real reason behind my using private variables is so they do not
appear in the epydoc generated documentation and confuse my users.

Regards,

Philippe




-- 
***
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
***

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


RE: Why I use private variables (WAS: RE:private variables a.k.a. name mangling?)

2005-01-24 Thread Jeremy Bowers
On Mon, 24 Jan 2005 15:35:11 -0600, Philippe C. Martin wrote:

 The real reason behind my using private variables is so they do not appear
 in the epydoc generated documentation and confuse my users.

You mean single or double underscores? I just checked and at least epydoc
2.1 doesn't include single-underscore values, but those aren't private
in sense we're talking in this thread (some form of compiler enforcement).

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


RE: Why I use private variables (WAS: RE:private variables a.k.a. name mangling?)

2005-01-24 Thread Philippe C. Martin
I used double underscore because I thought it was the correct way to name
private variables/methods - I will have to change those to single
underscore since that it the current methodology.

A private variable to me:
1) is internal to the processing of a class and needs not be accessed by
external or derivated objects. (I won't get into the
potential need of protected variables/methods - Python creators have not
made those distinctions for reasons that they believe are good and I'm not
the one to discuss them)
2) Must not be documented to library users as they're using it would
go againts 'law' 1).
3) I wish I had one, but there is only one Isaac Asimov after all :-)

Regards,

Philippe








On Mon, 24 Jan 2005 11:45:34 -0500, Jeremy Bowers wrote:

 On Mon, 24 Jan 2005 15:35:11 -0600, Philippe C. Martin wrote:
 
 The real reason behind my using private variables is so they do not appear
 in the epydoc generated documentation and confuse my users.
 
 You mean single or double underscores? I just checked and at least epydoc
 2.1 doesn't include single-underscore values, but those aren't private
 in sense we're talking in this thread (some form of compiler enforcement).

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


Re: Why I use private variables (WAS: RE:private variables a.k.a. name mangling?)

2005-01-24 Thread Steven Bethard
Philippe C. Martin wrote:
I used double underscore because I thought it was the correct way to name
private variables/methods - I will have to change those to single
underscore since that it the current methodology.
A private variable to me:
1) is internal to the processing of a class and needs not be accessed by
external or derivated objects.
[snip]
2) Must not be documented to library users as they're using it would
go againts 'law' 1).
Yeah, I use single-underscores for similar reasons, and so that 
PythonWin doesn't show my private variables in the drop-down list of 
object attributes.  I think for most uses, no name-mangling is required...

Of course, I could generate an arbitrary number of problem cases -- I 
just don't think they happen often in real code...

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