is a file open ?
for root, dirs, files in os.walk(path): for file in files: # ¿ is opened ? Best regards Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: is a file open ?
John Machin wrote: > Daniel Dittmar wrote: > >> luis wrote: >> >>> for root, dirs, files in os.walk(path): >>>for file in files: >>> # ¿ is opened ? >> >> >> >> On Linux and some other Unixes, you can probably read the /proc >> filesystem. >> >> On Windows, you'll probably get the quickest result by running >> handle.exe (http://www.sysinternals.com/Utilities/Handle.html). >> >> Either way, the information you'll get is restricted by your permissions. >> >> Either information will get stale really fast, so it's not suitable if >> your task is something like 'can I backup this directory or is someone >> writing to a file?' > > > If that's what the OP had in mind, the question might have been better > phrased as "given the path to a file, how can I tell if it is currently > opened by another process/thread", and better directed to OS-specifc > newsgroup(s). > there is a specific python function ? -- http://mail.python.org/mailman/listinfo/python-list
Re: is a file open ?
John Machin wrote: > Daniel Dittmar wrote: > >> luis wrote: >> >>> for root, dirs, files in os.walk(path): >>>for file in files: >>> # ¿ is opened ? >> >> >> >> On Linux and some other Unixes, you can probably read the /proc >> filesystem. >> >> On Windows, you'll probably get the quickest result by running >> handle.exe (http://www.sysinternals.com/Utilities/Handle.html). >> >> Either way, the information you'll get is restricted by your permissions. >> >> Either information will get stale really fast, so it's not suitable if >> your task is something like 'can I backup this directory or is someone >> writing to a file?' > > > If that's what the OP had in mind, the question might have been better > phrased as "given the path to a file, how can I tell if it is currently > opened by another process/thread", and better directed to OS-specifc > newsgroup(s). > there is a specific python function ? -- http://mail.python.org/mailman/listinfo/python-list
conecting with a MsAcces DB by dao
Hi I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 (reading first http://starship.python.net/crew/bwilk/access.html) I have writed the following code def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb;" conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I'm using it for reading tables or queries in a mdb file. With some mdb it works fine and return a no empty recordset, but with others mdb files, the recordsets are void (opening the tables or recorsets with Ms Access are not void). Some help is welcome, Thanks in advance Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
Iain King ha escrito: > luis wrote: > > Hi > > I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 > > (reading first http://starship.python.net/crew/bwilk/access.html) > > I have writed the following code > > > > def append_from_Access(self): > >try: > > import ... > > conn = win32com.client.Dispatch(r'ADODB.Connection') > > DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA > > SOURCE=C:/Afile.mdb;" > > conn.Open(DSN) > >except Exception, inst: > >... > >try: > > sql_statement='SELECT * FROM Mytable' > > rs = win32com.client.Dispatch(r'ADODB.Recordset') > > rs.Open(sql_statement, conn, 1, 3) > > while not rs.EOF: > > id=rs.Fields(colName.Value) #colName, valid column name > > ... > > rs.MoveNext() > > rs.Close() > > conn.Close() > > > > except Exception, inst: > > ... > > > > I'm using it for reading tables or queries in a mdb file. > > With some mdb it works fine and return a no empty recordset, but with > > others mdb files, the recordsets are void (opening the tables or > > recorsets with Ms Access are not void). > > Some help is welcome, > > Thanks in advance > > Luis > > I don't know if it's the problem your asking about, but your > rs.MoveNext() should be inside the while loop, no? Yes, is inside > > Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
Iain King ha escrito:
> luis wrote:
> > Iain King ha escrito:
> >
> > > luis wrote:
> > > > while not rs.EOF:
> > > > id=rs.Fields(colName.Value) #colName, valid column name
> > > > ...
> > > > rs.MoveNext()
> > > > rs.Close()
> > > > conn.Close()
> > >
> > > I don't know if it's the problem your asking about, but your
> > > rs.MoveNext() should be inside the while loop, no?
> > Yes, is inside
> > >
>
> You mean, it is inside the while loop in your code, but you made a
> mistake copying it into your post? In the code you posted it is not
> inside the while loop - it would have to be indented one more level for
> that.
>
> Iain
this is te correct identation
def append_from_Access(self):
try:
import ...
conn = win32com.client.Dispatch(r'ADODB.Connection')
DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA
SOURCE=C:/Afile.mdb;"
conn.Open(DSN)
except Exception, inst:
...
try:
sql_statement='SELECT * FROM Mytable'
rs = win32com.client.Dispatch(r'ADODB.Recordset')
rs.Open(sql_statement, conn, 1, 3)
while not rs.EOF:
id=rs.Fields(colName.Value) #colName, valid column name
...
rs.MoveNext()
rs.Close()
conn.Close()
except Exception, inst:
...
I think my problem must be with ado and dao.
Now I have run makepy utility and select Microsoft ActiveX Data Objects
2.5 Library, perhaps I must also select Microsoft DAO3.5 Object Library
and write
win32com.client.Dispatch("DAO.DBEngine.35") for Access 97 or
win32com.client.Dispatch(r'ADODB.Connection') for Acess 2000
Do you know is it possible ?
luis
--
http://mail.python.org/mailman/listinfo/python-list
Re: conecting with a MsAcces DB by dao
Iain King ha escrito:
> luis wrote:
> > Iain King ha escrito:
> >
> > > luis wrote:
> > > > Iain King ha escrito:
> > > >
> > > > > luis wrote:
> > > > > > while not rs.EOF:
> > > > > > id=rs.Fields(colName.Value) #colName, valid column name
> > > > > > ...
> > > > > > rs.MoveNext()
> > > > > > rs.Close()
> > > > > > conn.Close()
> > > > >
> > > > > I don't know if it's the problem your asking about, but your
> > > > > rs.MoveNext() should be inside the while loop, no?
> > > > Yes, is inside
> > > > >
> > >
> > > You mean, it is inside the while loop in your code, but you made a
> > > mistake copying it into your post? In the code you posted it is not
> > > inside the while loop - it would have to be indented one more level for
> > > that.
> > >
> > > Iain
> >
> > this is te correct identation
> >
> > def append_from_Access(self):
> >try:
> > import ...
> > conn = win32com.client.Dispatch(r'ADODB.Connection')
> > DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA
> > SOURCE=C:/Afile.mdb;"
> > conn.Open(DSN)
> >except Exception, inst:
> >...
> >try:
> > sql_statement='SELECT * FROM Mytable'
> > rs = win32com.client.Dispatch(r'ADODB.Recordset')
> > rs.Open(sql_statement, conn, 1, 3)
> > while not rs.EOF:
> > id=rs.Fields(colName.Value) #colName, valid column name
> > ...
> > rs.MoveNext()
> > rs.Close()
> > conn.Close()
> >
> > except Exception, inst:
> > ...
> >
> > I think my problem must be with ado and dao.
> > Now I have run makepy utility and select Microsoft ActiveX Data Objects
> > 2.5 Library, perhaps I must also select Microsoft DAO3.5 Object Library
> > and write
> > win32com.client.Dispatch("DAO.DBEngine.35") for Access 97 or
> > win32com.client.Dispatch(r'ADODB.Connection') for Acess 2000
> > Do you know is it possible ?
> > luis
>
> Well, without being able to test on your system I don't think I can
> give you any real advice. This is the module I use to interface with
> Access:
>
> Access.py
> ---
> import win32com.client
> from win32com.client import constants
>
> def isWriteable(field):
> """Is given Field writeable?"""
> return field.Attributes & 4
>
>
> class Access(object):
> def __init__(self, filename, password=""):
> self._filename = filename
> self._connection = win32com.client.Dispatch(r'ADODB.Connection')
> if password:
> self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA
> SOURCE=%s;Jet
> OLEDB:Database Password=%s;' % (filename, password)
> else:
> self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA
> SOURCE=%s;' %
> (filename)
>
> def Query(self, query):
> self._connection.Open(self._DSN)
> rs = win32com.client.Dispatch(r'ADODB.Recordset')
> rs.Open(query, self._connection, 1, 3)
> fields = []
> for x in xrange(rs.Fields.Count):
> fields.append(rs.Fields(x).Name)
> if rs.EOF:
> data = []
> else:
> data = rs.GetRows()
> rs.Close()
> self._connection.Close()
> return fields, data
>
>
> def Add(self, table, records):
> """Adds records to table."""
> self._connection.Open(self._DSN)
> rs = win32com.client.Dispatch(r'ADODB.Recordset')
> rs.Open(table, self._connection, 1, 3)
> unwriteables = []
> for record in records:
> rs.AddNew()
> unwriteable = []
> for i in xrange(len(record)):
> if isWriteable(rs.Fields(i)):
> rs.Fields(i).Value = record[i]
> else:
> unwriteable.append(rs.Fields(i).V
ctypes: error passing a list of str to a fortran dll
I'm using ctypes to call a fortran dll from python. I have no problems passing integer and double arryas, but I have an error with str arrys. For example: StringVector = c_char_p * len(id) # id is a list of strings Id_dat=StringVector() for i in range(len(Id)): ...Id_dat[i]=id[i] n=c_int(len(Id_dat)) myDll = windll.LoadLibrary(org) myDll.myFunc(byref(n), byref(Id_dat)) and then ValueError: Procedure probably called with not enough arguments (4 bytes missing) In a similar way I have bo problemns with int or double arryas Some suggestions are wellcome ! -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes: error passing a list of str to a fortran dll
On 5 jun, 06:15, Charles Sanders <[EMAIL PROTECTED]> wrote: > luis wrote: > > I'm using ctypes to call afortrandllfrom python. I have no problems > > passing integer and double arryas, but I have an error with str arrys. > > For example: > > [snip] > > I do not know about MicrosoftFortrancompilers (your mention > ofdllindicates you are probably using MS), nor much about > Python, but the C equivalent of a givenFortrancall is operating > system and compiler dependent. You should consult theFortran > compiler manual for the compiler used to create theDLL. > > Despite this, many (but not all) C toFortraninterfaces have > the following characteristics > > + C name isFortranname in lower case > +FortranREAL, DOUBLE PRECISION, INTEGER etc parameters > are pointers to the parameter in C, ie float*, etc > +FortranREAL etc arrays are pointers in C (same as > C arrays decay to pointers). > +FortranCHARACTER and CHARACTER arrays are passed as TWO > parameters, one a pointer to the start of the variable > or array, and the other the length as an integer, not > a pointer. The length parameters follow all other > parameters, in order of the character variables/arrays. > > Variations I have seen (all on Unix) include using upper case > instead of lower, prepending (or postpending) an underscore (or > other character(s)) to the subroutine or function name, and > using special "character descriptors" (packing address and > length into one "word") for character variables. There are > almost certainly more variations that I have not seen. > > For example, given aFORTRANdeclaration > > SUBROUTINE X( CV, RV, CA, N ) > CHARACTER*(*) CV > REAL RV > CHARACTER*(*) CA(*) > INTEGER N > > The C equivalent is likely to be > > void x( char *pcv, float *prv, char *pca, int *pn, > int lv, int la) > > Where lv will hold the length of cv and la the length of > each element of ca (required to be the same for all elements > of the array).Fortranuses fixed length character strings, > padded with blanks. > > Given the error message > > > ValueError: Procedure probably called with not enough > > arguments (4 bytes missing) > > I suspect that yourFortrancompiler is one of the many which > do this, and the missing 4 bytes are the integer length of > each element of the character array. > > Also, I noticed you seem to be passing an array of character > pointers rather than an array of characters. It is doubtful thatFortrancan > handle this. You will probably have to pad the strings > to a maximal length with spaces, concatanate then into one big > string, and pass this by reference together with their padded > length. YourFortranmay (but probably won't) have extensions > that allow you to pass an array of character pointers. > > Charles The solution proposed by Jugoslav Dujic, from comp lang fortran is #Python script calling fortran subroutine from ctypes import * ap = windll.LoadLibrary(self.locationDll) ap.TEST_02.restype=None myCadena='D:\BBDD\PythonScripts\pru.txt' strLen=len(myCadena) pf_myCadena = c_char_p(myCadena) pf_srLen = c_int(strLen) ap.TEST_02(pf_myCadena,pf_srLen) !fortran dll subroutine TEST_02(s) !DEC$ ATTRIBUTES DLLEXPORT :: TEST_02 !DEC$ATTRIBUTES REFERENCE:: s !INTEGER(4):: n CHARACTER(*):: s open (unit=31,file=trim(s)) write(31,'(f0.1)') 1.0 write(31,*) trim(s) write(31,'(i0)') len_trim(s) close(31) return END subroutine Regards -- http://mail.python.org/mailman/listinfo/python-list
dislin titlin and string decode
Hello!
I have an unespectedn result with dislin titlin
dislin.metafl ('WMF')
dislin.disini ()
a="Andrés or Ramón"
dislin.titlin (a.encode("Latin-1"), 1)
# not error raised, is ok
dislin.disfin ()
In the output file all is ok but the title is
Andr s or Ram n
Thanks in advance!
--
http://mail.python.org/mailman/listinfo/python-list
Re: dislin titlin and string decode
the code is:
#!/usr/bin/env python
def try_dislin():
...import dislin
...dislin.metafl ('WMF')
...dislin.errdev ('FILE')
...dislin.disini ()
...dislin.errmod('PROTOCOL','ON')
...dislin.hwfont ()
...dislin.pagera ()
...dislin.pagfll (255)
...dislin.color('BLACK')
...dislin.axspos (500, 1600)
...dislin.axslen (2200, 1200)
...
...dislin.name...('x','X')
...dislin.name...('y','Y')
...
...dislin.ticks (10, 'X')
...dislin.ticks (10, 'Y')
...dislin.labels ('FLOAT','X')
...dislin.labels ('FLOAT','Y')
...dislin.incmrk(1)
...dislin.hsymbl (15)
...dislin.chacod('STANDARD')
...dislin.polcrv('LINEAR')
...x=[1.,2.,3.]
...y=[1.,2.,3.]
.
...a=unicode("Ramón y Andrés",'Latin-1')
...dislin.titlin (a.encode('Latin-1'), 1)
...
...min_x_axis=1.
...max_x_axis=3.
...min_y_axis=1.
...max_y_axis=3
...
...xstep=(max_x_axis - min_x_axis)/10.
...ystep=(max_y_axis - min_y_axis)/10.
...dislin.graf (min_x_axis,max_x_axis,min_x_axis,xstep \
..,min_y_axis,max_y_axis,min_y_axis,ystep)
...
...dislin.title()
...
...dislin.curve(x,y, len(x))
...dislin.color ('foreground')
...dislin.dash...()
...dislin.xaxgit ()
...dislin.disfin ()
try_dislin()
print 'end'
--
http://mail.python.org/mailman/listinfo/python-list
Re: dislin titlin and string decode
On 19 mayo, 12:56, luis <[EMAIL PROTECTED]> wrote:
> Hello!
>
> I have an unespectedn result with dislin titlin
>
> dislin.metafl ('WMF')
> dislin.disini ()
>
>
> a="Andrés or Ramón"
> dislin.titlin (a.encode("Latin-1"), 1)
> # not error raised, is ok
>
>
> dislin.disfin ()
>
> In the output file all is ok but the title is
>
> Andr s or Ram n
>
> Thanks in advance!
The problem was the value of dislin.chacod. This must be 'ISO1' not
the default ('STANDAR')
--
http://mail.python.org/mailman/listinfo/python-list
Windows error 126 loading a dll on windows 2000
Hi! I'm using ctypes with python 2.4 on windows xp the code if exists(join(getcwd(),'statistics.dll')): ...ap=windll.LoadLibrary(join(getcwd(),'statistics.dll')) works fine but on windows 2000, the some code raise the windows error 126, it can't load the module statistics.dll thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
unable to install gdal
Hi On Windows xp sp2 and python 2.4 Yesterday I running old versions of gdal, and I try to upgrade I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 I follow install's instructions from http://trac.osgeo.org/gdal/wiki/GdalOgrInPython, all is ok, I set path and path_data variables with correct values, but whe I run a script, an error raises from osgeo import ogr File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? import _ogr ImportError: DLL load failed: process not found Also I try with instructions from http://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gdalinstall.html I move _gdal.pyd (and the others *.pyd) from my Python installation's (C:\Python24\Lib\site-packages\osgeo) into my Python installation's DLLs folder (C:\Python24\DLLs). When I run the script the error message persists. Some help is welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: unable to install gdal
On 9 mar, 16:37, luis <[EMAIL PROTECTED]> wrote: > Hi > > On Windows xp sp2 and python 2.4 > > Yesterday I running old versions of gdal, and I try to upgrade > > I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe > I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 > > I follow install's instructions > fromhttp://trac.osgeo.org/gdal/wiki/GdalOgrInPython, > all is ok, I set path and path_data variables with correct values, but > whe I run a script, an error raises > > from osgeo import ogr > File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? > import _ogr > ImportError: DLL load failed: process not found > > Also I try with instructions > fromhttp://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gda... > I move _gdal.pyd (and the others *.pyd) from my Python installation's > (C:\Python24\Lib\site-packages\osgeo) into my Python installation's > DLLs folder (C:\Python24\DLLs). > When I run the script the error message persists. > > Some help is welcome. If I install on a XP without previous installation of gdal, the installation works fine. Perhaps is a problem with XP's registry -- http://mail.python.org/mailman/listinfo/python-list
Re: unable to install gdal
On 10 mar, 09:49, luis <[EMAIL PROTECTED]> wrote: > On 9 mar, 16:37, luis <[EMAIL PROTECTED]> wrote: > > > > > Hi > > > On Windows xp sp2 and python 2.4 > > > Yesterday I running old versions of gdal, and I try to upgrade > > > I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe > > I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 > > > I follow install's instructions > > fromhttp://trac.osgeo.org/gdal/wiki/GdalOgrInPython, > > all is ok, I set path and path_data variables with correct values, but > > whe I run a script, an error raises > > > from osgeo import ogr > > File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? > > import _ogr > > ImportError: DLL load failed: process not found > > > Also I try with instructions > > fromhttp://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gda... > > I move _gdal.pyd (and the others *.pyd) from my Python installation's > > (C:\Python24\Lib\site-packages\osgeo) into my Python installation's > > DLLs folder (C:\Python24\DLLs). > > When I run the script the error message persists. > > > Some help is welcome. > > If I install on a XP without previous installation of gdal, the > installation works fine. > > Perhaps is a problem with XP's registry If I run the script in the dos line command (>> python script_name.py) a final windows error's message says curls_multi_cleanup pocedure don`t find entry point in libcurl.dll I have found 2 programs using other versions libcurl.dll In the PATH environment variable I insert C:\gdalwin32-1.5\bin before paths those programs, and the error has disappeared -- http://mail.python.org/mailman/listinfo/python-list
maintain 2 versions of python on my computer
Hi I am not an expert in programming and using Python for its simplicity I have 2 versions of python installed on my computer (windos xp) to begin the transition from version 2.4 to 2.6 or 3. maintaining the operability of my old scripts Is there any way to indicate the version of the python interpreter must use a script? thanks -- http://mail.python.org/mailman/listinfo/python-list
IDLEX association
Hi When I double click a .py file, a windows appears and immediately disappears. How can I associate the .py file extension to the IDLEX EDITOR? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Style().configure don't works for all widgets
Hi
Why
ttk.Style().configure(".", font=('Courier New', 30, "bold"))
works for Button and Label widgets (and maybe others) and don't works for Entry
widget?
Example in Python 3:
from tkinter import *
from tkinter import ttk
from tkinter import font
root = Tk()
ttk.Style().configure(".", font=('Courier New', 30, "bold"))
ttk.Entry(root).grid() # don't works
ttk.Label(root, text="my text").grid() # works OK
ttk.Button(root, text="some text").grid() # works OK
root.mainloop()
Thank you
--
https://mail.python.org/mailman/listinfo/python-list
Re: logging as root using python script
Raghul wrote: > What I need is when I execute a script it should login as root and > execute my command and logout from root to my existing account. I'm not sure of what you need, so I'll assume your *whole* .py script needs root priviledges. In this case, you can configure sudo(8) or use su(1). For example, the script below does nothing special: | #!/usr/bin/env python | | print "Hello world!" You can run it with higher priviledges if you use sudo(8): $ chmod 755 hello.py $ sudo ./hello.py Or you can use su(1): $ su - root -c ./hello.py You can configure sudo(8) to not prompt for any password, BTW. Cheers! -- Luis Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: logging as root using python script
Martin Franklin wrote: > another alternative would be setuid I also thought about making the script setuid root, but I'm under the impression that Linux (at least) won't honor the suid bit on a script. That's from memory though. Cheers! -- http://mail.python.org/mailman/listinfo/python-list
Help: python 3.3.3 (AMD64) scripts fail as non-admin user on Windows Server 2012 R2
I've installed python for all users with full permissions to all users (see picture). Python runs for all users. However, scripts only work when I run as Administrator. Running a script always results in an "ImportError: cannot import name" error. Here, for example, is the output of "pip -h" run as an unprivileged user: pip : Traceback (most recent call last): At line:1 char:1 + pip -h 2>&1 | Out-File -FilePath pip.txt + ~~~ + CategoryInfo : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError File "C:\Open\Python33\lib\runpy.py", line 160, in _run_module_as_main "__main__", fname, loader, pkg_name) File "C:\Open\Python33\lib\runpy.py", line 73, in _run_code exec(code, run_globals) File "C:\Open\Python33\Scripts\pip.exe\__main__.py", line 5, in ImportError: cannot import name main I get regular output when I run "pip -h" as Administrator: Usage: pip [options] Commands: install Install packages. uninstall Uninstall packages. freeze Output installed packages in requirements format. listList installed packages. showShow information about installed packages. search Search PyPI for packages. wheel Build wheels from your requirements. zip DEPRECATED. Zip individual packages. unzip DEPRECATED. Unzip individual packages. bundle DEPRECATED. Create pybundles. helpShow help for commands. General Options: -h, --help Show help. -v, --verbose Give more output. Option is additive, and can be used up to 3 times. -V, --version Show version and exit. -q, --quiet Give less output. --log-filePath to a verbose non-appending log, that only logs failures. This log is active by default at C:\Users\Safe Administrator\pip\pip.log. --log Path to a verbose appending log. This log is inactive by default. --proxy Specify a proxy in the form [user:passwd@]proxy.server:port. --timeout Set the socket timeout (default 15 seconds). --exists-action Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup. --certPath to alternate CA bundle. I can't figure out the issue: please help! <>-- https://mail.python.org/mailman/listinfo/python-list
Expert Advice
Hi Everyone, A number of friends in the community recommended i email this group regarding some obstacles im running into regarding a Python/Django dilemma :). Im currently representing a e-Plushing firm who has built an amazing custom ebook publishing platform in Django and Python. We are now looking for a Python engineer who has dabbled in NoSQL databases. This person will understand programming languages both static and dynamic typing. They offer a great work environment as they have a nice loft in Midtown in addition to challenging/custom work. Below i have included additional details if you know of anyone that might be interested. Ps. We have a great referral program as well. Our ebook publishing platform is built on Django and LAMP (for P in ['Python']) - and the demand is growing! We're looking for a senior software engineer who's passionate about building and shipping products that are great inside and out. As a senior team member, you'll ensure our product enjoys high-availability, scalability, and the other expected non-functional requirements through peer review and leveraging cloud infrastructure. You'll also support our journey towards continuous delivery inclusive of iterative development, automated testing (CI), modern configuration management using chef, and push-button deployments with confidence. About you: You love technology and good engineering as much as shipping great products - and deftly balance these concerns. You're a Python expert and code for fun. You've probably dabbled in NoSQL databases, know multiple programming languages both static and dynamic typing (and pros/cons of each), have tried a variety of web servers and frameworks, understand the power and challenges of different caching strategies, are a go-to for CS fundamentals, and contribute to open source projects. You constructively initiate improvements. You also don't shy away from Linux systems operations where it butts up against development concerns such as redundancy with auto-failover, efficient resource utilization, performance optimization, data management, apache configuration, application monitoring, log file aggregation (e.g., using scribe), security, capacity and scaling concerns - i.e., approaching devops from the development side. You enjoy being a hands-on individual contributor and also have great skills mentoring peers/colleagues - a team player who's well respected due to your technical abilities and willingness to help other team members without the ego. You thrive in a fast-paced yet thoughtful startup environment. Requirements 8+ years in software development in Linux - years of experience are necessary to design robust architectures Python expertise required - (open source) samples will be requested Experience building and maintaining distributed, scale-out, high performant web-based systems on Linux required Have solid CS and OO fundamentals Strong and effective communication skills including with remote team members Have created and consumed RESTful APIs Cloud experience with AWS or comparable required Iterative (agile) development experience required Must have a passion for automated testing Python web framework and MVC pattern usage required; Django a plus; built your own web framework a major plus Push-button deployment experience a plus Experience with Celery and RabbitMQ a plus Knowledge of ePub and HTML5 standards a plus Perks Fun coworkers, great mentors Convenient mid-town Manhattan "loft" Lots of fun with Apple products and ereaders luis perez | principal winter wyman companies - technology staffing tel: 212.616.3582| fax: 212.616.3592 | aim: lpcnn23 I Please consider the environment before printing this email -- http://mail.python.org/mailman/listinfo/python-list
wx mouse states
Hello i using GetMouseState() to get the position in X and Y of the mouse pointer over time with the use of ScreenToCliente to get local windows coordinates in windows in work like a charm no problem the app is fast and works how it should. But on macos I get this damn error msg ms = wx.GetMouseState() Attribute error: 'module object has no attribute 'GetMouseState' I using the laster version wxwindows 2.6 on both windows and mac os x 10.4.5 Any help folks :D -- http://mail.python.org/mailman/listinfo/python-list
IMAP4 search with special characters
Hi all,
I have a problem when searching for text with special characters in
e-mails in an IMAP server. I'm using imaplib in python 2.4.3 and I can't
get this code working:
# first connect and login
conn = IMAP4(my_server)
conn.login(my_user, my_pass)
# now select INBOX
conn.select('INBOX')
# and search for messages (the first parameter of "search" is the
encoding, which defaults to None)
conn.search(None, '(ALL)') # output: ('OK', ['1 2 3'])
# That works perfectly and I get the 3 messages that I have in my Inbox:
# Now I want to search for messages with special characters. This works
(still no special characters in my search):
conn.search(None, '(BODY gasse)')
# and even this:
conn.search('ISO-8859-1', '(BODY gasse)')
# but not this (there comes the 'ö'):
conn.search('ISO-8859-1', '(BODY Lemböckgasse)')# error: SEARCH
command error: BAD ['Bogus criteria list in SEARCH']
# After having read the IMAP4 documentation I thought this could work:
conn.search('ISO-8859-1', '(CHARSET ISO-8859-1 BODY Lemböckgasse)')
# I tried everything that came up to my mind, getting always the same
error. For instance:
conn.search(None, '(CHARSET ISO-8859-1 BODY Lemböckgasse)')
conn.search(None, '(BODY Lemb\xf6ckgasse)')
conn.search(None, '(BODY Lemböckgasse)'.encode('ISO-8859-1')) # here I
get the error "can't decode byte 0xf6 in position 10"
conn.search('ISO-8859-1', '(BODY Lemböckgasse)'.encode('ISO-8859-1'))
And so on. Does anybody have the remotest idea what I'm doing wrong and
how I could find my e-mail?
Thanks in advance,
Luis Corrales
--
http://mail.python.org/mailman/listinfo/python-list
Re: A problem from a Vim user
manuhack wrote:
> When I use raw_input('Please type something.\n') in the python 2.4
> command line windows, it doesn't have any problem. However, when I run
> the same command in vim 7 as :py raw_input('Please type something.\n'),
> there is an EOFError: EOF when reading a line. Is there a way to use
> that command within vim without raising errors?
>
> Thanks a lot.
>
You should read :help python-input
On my version (Vim 7.0.17), it says that input() and raw_input() are
not yet supported.
So, submit a patch to the vim folks!
-Luis
--
http://mail.python.org/mailman/listinfo/python-list
rare error with python at execution
I was trying the win32api to gather some
system information.
But now I get this error everytime I run a
script and I have no idea. It can be a simple print ‘hello’ that it
wont work
This is the error I get
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "D:\Archivos de
programa\ActiveState Komodo 3.5\lib\support\dbgp\bin\pydbgp.py", line 61,
in ?
if
os.environ.has_key("PYDBGP_PATH"):
AttributeError: 'module' object has no
attribute 'environ'
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to depress the output of an external module ?
On Tuesday, 26.12.06 at 21:28, Steven D'Aprano wrote: > > # WARNING: untested > def run_without_stdout(*args, **kwargs): > function = args[0] > args = args[1:] > savestdout = sys.stdout > sys.stdout = cStringIO.StringIO() > result = None > try: > result = function(*args, **kwargs) > finally: > # don't forget to restore stdout, or you > # really will regret it... > sys.stdout = savestdout > return result > There's no need for savestdout. There's a backup copy in sys.__stdout__ -Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get function names from the file
Try the following:
def printFoo():
print "Foo"
def printFOO():
print "FOO"
functions = ("printFoo", "printFOO")# list or tuple of strings from
file, or wherever
for function in functions:
call = function + "()"
eval(call)
--
http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance
Hi Thomas, When an object is created, the __init__ function will be called. Since you didn't define it in Foobar, the search path finds the __init__ function in Foo, so that's the one that is called. The second __init__ in Bar is masked since it comes second in the inheritance list.. If you want to call both constructors, then what you did is fine! The fact that 'x' comes from the Bar object is ok too. That's what you told python to do. What did you expect if you are setting 'x' twice? I mean, when I type the following two statements into the interpreter: a = 1 a = 2 then after those two statements execute, the value of a is naturally 2, not 1. Same with your 'x'. And what is wrong with the explicit calls to each constructor? After all, in python, explicit is better than implicit. If you don't believe me, type "import this" in your interpreter: >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! -- http://mail.python.org/mailman/listinfo/python-list
Re: Attached images by plain email.
Hi Gaz, Perhaps this will help? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52243 -- http://mail.python.org/mailman/listinfo/python-list
Duck Typing and **kwds
Hi there.
I just tried this test:
def f(**kwds):
print kwds
import UserDict
d = UserDict.UserDict(hello="world")
f(**d)
And it fails with a TypeError exception ("f() argument after ** must be a
dictionary"). I find that weird, as UserDict should support all protocols that
dict supports, yet it doesn't seem to support ** unpacking. If instead of
UserDict I use a derivate class from dict (class mydict(dict):pass), the **
operator works as expected. It also works if I execute f(**dict(d)) instead.
Is that behavior expected? Is there any reason (performance, perhaps?) to break
duck-typing in this situation?
Regards,
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
--
"Al mundo nuevo corresponde la Universidad nueva"
UNIVERSIDAD DE LA HABANA
280 aniversario
--
http://mail.python.org/mailman/listinfo/python-list
Re: Best way to generate alternate toggling values in a loop?
On Thursday 18 October 2007 09:09, Grant Edwards wrote: > I like the solution somebody sent me via PM: > > def toggle(): > while 1: > yield "Even" > yield "Odd" > That was me. Sorry, list, I meant to send it to everyone but I my webmail didn't respect the list* headers :(. Thanks, Grant! -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: vote for Python - PLEASE
On Thursday 18 October 2007 22:59, [EMAIL PROTECTED] wrote: > > but > > I'd rather that people got the message that they should do more python > > development work!) > > Maybe the Python community doesn't need your help. He did try to help, in a morally questionable way, but still in good faith (I believe). I wouldn't treat him so harshly, even though I didn't like being asked to lie. Anyway, I went to vote. I do use python with mysql. Python seems to be winning by a 16% margin, more or less. Impressive... but now I have to wonder how many people lied. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: shouldn't 'string'.find('ugh') return 0, not -1 ?
> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found,
> should't the .find method return 0 rather than -1?
I belive str.find should return the first position where the substring appears.
If "string".find("ugh") were to return 0, how would you differentiate from
"ugh".find("ugh")? That one *should* return 0.
> this breaks the
>
> if check.find('something'):
> do(somethingElse)
>
> idiom, which is a bit of a pity I think.
It breaks the idiom because you are speaking the wrong language.
You should be doing:
if "something" in "string":
do(something())
wich is clearer IMHO.
> cheers,
>
> -jelle
See ya,
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
"Al mundo nuevo corresponde la Universidad nueva"
UNIVERSIDAD DE LA HABANA
280 aniversario
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to clear up a List in python?
vbgunz wrote: > Steve, I have no qualm with Fredrik over this '''if you don't know how > to do things, you don't need to post.''' but this ''' if you know why > this is about the dumbest way to do what you're doing, and you're > posted this on purpose, you really need to grow up.'''. Well, given that you did post it on purpose and had no "intent to mess anyone up over it", it is clear that the antecedent in Fredrik's if-statement is not satisfied and therefore your mind should've skipped the consequent statement when reading his response. Why get so upset about something that didn't even apply to you? :-) -Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: hide python window
Bell, Kevin wrote: > When I run a script, how can I make it run in the background? I don't > want to see the command window because it runs all day. I'm on > windows... > > Hi Kevin, Rename your kevin_script.py to kevin_script.pyw (so that it runs with pythonw.exe instead of python.exe). -Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: translating Python to Assembler
I second Wim's opinion. Learn python as a high level language, you won't regret it. About google, I'll give you a little gtip: > > For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) Instead of searching 'python.pdb' try the query "filetype:pdb python", or even "python pdb" (quoted). The first one whould give you files with pdb extension and python in the name or contents, and the second one (quoted) should return pages with both words together, except for commas, spaces, dots, slashs, etc. However... one of the second query results is this thread in google groups... not a good sign. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie Quoting Wim Vander Schelden <[EMAIL PROTECTED]>: > Python modules and scripts are normally not even compiled, if they have > been, > its probably just the Python interpreter packaged with the scripts and > resources. > > My advice is that if you want to learn Python, is that you just read a book > about > it or read only resources. Learning Python from assembler is kind of... > strange. > > Not only are you skipping several generations of programming languages, > spanned > over a period of 40 years, but the approach to programming in Python is so > fundamentally different from assembler programming that there is simply no > reason > to start looking at if from this perspective. > > I truly hope you enjoy the world of high end programming languages, but > treat them > as such. Looking at them in a low-level representation or for a low-level > perspective > doesn't bear much fruits. > > Kind regards, > > Wim > > On 1/22/08, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > > > My expertise, if any, is in assembler. I'm trying to understand Python > > scripts and modules by examining them after they have been > > disassembled in a Windows environment. > > > > I'm wondering if a Python symbols file is available. In the Windows > > environment, a symbol file normally has a PDB extension. It's a little > > unfortunate that Python also uses PDB for its debugger. Google, for > > whatever reason, wont accept queries with dots, hyphens, etc., in the > > query line. For example a Google for "python.pdb" returns +python > > +pdb, so I get a ridiculous number of returns referring to the python > > debugger. I have mentioned this to Google several times, but I guess > > logic isn't one of their strong points. :-) > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- "Al mundo nuevo corresponde la Universidad nueva" UNIVERSIDAD DE LA HABANA 280 aniversario -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 14 January 2009 02:22:45 am Paul Rubin wrote: > 2. There is also nothing inherent in a dynamic OO language that says > that class descriptors have to be mutable, any more than strings have > to be mutable (Python has immutable strings). I agree that being able > to modify class descriptors at runtime is sometimes very useful. The > feature shouldn't be eliminated from Python or else it wouldn't be > Python any more. But those occasions are rare enough that having to > enable the feature by saying (e.g.) "@dynamic" before the class > definition doesn't seem like a problem, both for encapsulation Why don't you do it backwards? You *can* implement a metaclass that will remove the dynasmism from its instances. Do it - I can give you a starting point if you wish. But most of us are very happy with the dynamic nature of python... I chose python _because_ of it. > and because it can also improve performance. Btw, for performance, there is __slots__, with the side-effect that it forbids attribute creation 'on the fly'. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 13 January 2009 09:57:04 pm Terry Reedy wrote: > Russ P. wrote: > public = no leading underscore > private = one leading underscore > protected = two leading underscores Aren't the last two reversed? protected = one leading underscore [both you and your subclasses should access it] private = two leading underscores (name munging) [only you should access - implementation detail.] -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 13 January 2009 10:32:54 pm James Mills wrote: > Should Python get strict and enforce access control > of object members ? No. Why ? I can think of several > reasons. > > Give me one use-case where you strictly require > that members of an object be private and their > access enforced as such ? Devil's advocate here - I think I can give you one: when you need to share some objects with potentially untrusted code (like, a plugin system). You can't, and you shouldn't, expect that the user will know what plugins he should or shouldn't load, and you shouldn't blame him/her when your app stops working because you failed to protect it's internals from malicious plugins (think web browser). Of course... in that scenario, the public/private distinction is the least of the concerns... and whatever is done to solve them will likely make irrelevant if the members are private or public. But, for trusted code? Or at least code known at compile time? It's just not worth it... pylint should take care of that - and if it doesn't, the OP should go fix it. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 14 January 2009 12:57:42 am James Mills wrote: > Russ: > > 1. Quit while you're ahead. > 2. OOP is encapsulating data and functionality into a single grouping > (object). > 3. Other features more recently developed by OO languages such as > Polymorphism, Access Control (a type of encapsulation), Inheritance > and Multiple Inheritance are all irrelevant and OO languages either > implement all or a subset of these features and each do so > differently. To further your point, I'd say that python _doesn't_ have polymorphism. It doesn't need it - the natural, expected, "OOP" behavior is always there, you cannot break it. A dog will always bark and a cat will always meow, regardless of the context and the inheritance relation between a cat and a dog (there should be none, but I couldn't think of a better example than the broken 'a cat is a dog'... please bear with me). If the very concept of polymorphism is superfluous in python, would that make python 'less' OOP? Judging by this thread, I'd guess that Russ believes that languages like C# are closer to his OOP ideal... and guess what, C# not only needs a word for the concept of "objects should behave as you expect them to behave - we want no barking cats, ever", but it is even not polymorphic by default (the cursed "virtual" keyword). -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 14 January 2009 11:18:51 am Paul Rubin wrote: > Luis Zarrabeitia writes: > > when you need to share some objects with potentially untrusted code > > (like, a plugin system). You can't, and you shouldn't, expect that the > > user will know what plugins he should or shouldn't load, and you > > shouldn't blame him/her when your app stops working because you failed to > > protect it's internals from malicious plugins (think web browser). > > Python is not set up for this even slightly. Java attempts it, with > mixed success. I know. I find it sad, though. Also, I find it not a priority. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 14 January 2009 11:45:46 am Paul Rubin wrote:
> Luis Zarrabeitia writes:
> > Why don't you do it backwards?
> > You *can* implement a metaclass that will remove the dynasmism from its
> > instances. Do it - I can give you a starting point if you wish.
>
> That's kind of interesting, how does it work?
Proof of concept, that breaks on inheritance (can't call 'super'), but it took
me just a few minutes to cook. If you aren't that paranoid, you could get rid
of the 'currentframe' and 'code' hacks. This creates a class "MyClass" which
instances cannot be modified. I once gave my students the homework of
creating a metaclass that would type-check all the assignments to its
members - so that the types wouldn't change.
import inspect
class ImmutableType(type):
def __init__(self, *args, **kwds):
super(ImmutableType, self).__init__(*args, **kwds)
initmethod = self.__init__.im_func
def setattr(instance, attr, value):
callee = inspect.currentframe(1) #letting the initializer
if callee.f_code is initmethod.func_code: #initialize the object
super(self, instance).__setattr__(attr, value)
else:
raise Exception("Object is immutable")
self.__setattr__ = setattr # Heh, I'm adding a dynamic attribute :D
class MyClass(object):
__metaclass__ = ImmutableType
a = 5
def __init__(self, value):
print "assigning b"
self.b = value
print self.b
m = MyClass("can't change")
print m.a, m.b # these work
m.b = 6 # and these dont.
m.c = 8
==
> > But most of us are very happy with the dynamic nature of python... I
> > chose python _because_ of it.
>
> I like it too, since it is indispensable in some situations. But,
> those situations are uncommon enough that I don't mind typing a few
> extra keystrokes to turn the dynamism on.
I find the opposite to be true.
I _usually_ want the dynamism. Even if I'm not using it - I rely on the
dynamism to be there for when I need it.
> > Btw, for performance, there is __slots__,
>
> That is a good point, we somehow lost sight of that in this thread.
>
> > with the side-effect that it forbids attribute creation 'on the
> > fly'.
>
> I have had the impression that this is a somewhat accidental side
> effect and shouldn't be relied on.
Yes, accidental side effect.
But I see no _necessary_ harm on tacking extra attributes to an existing
object - specially if you are going to use them pretty close to the creation.
I use them, a lot, specially when writing decorators... Many times I just
want to 'mark' the decorated functions so I can inspect those marks later.
I'd rather have a semi-private namespace for each pair ([group of]calling
function[s], object), but it is way easier (and so far, maintanable) to just
add an appropriately named dynamic attribute to the object.
Of course there can be harm - but the fault lies on the user and not the tool.
I specially dislike that I can't add dynamic attributes to an object().
--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 14 January 2009 12:54:13 pm Paul Rubin wrote: > Bruno Desthuilliers writes: > > You'll find successful "monster" projects written in > > languages that are even more permissive than Python (C anyone ?), > > Could you name one written in C? hmm... http://kernel.org -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting Paul Rubin <"http://phr.cx"@NOSPAM.invalid>: > Often, the Python program crashes halfway through, even though I > tested it on a few megabytes of data before starting the full > multi-gigabyte run, because it hit some unexpected condition in the > data that could have been prevented with more compile time checking > that made sure the structures understood by the one-off script matched > the ones in the program that generated the input data. Wait, do you _really_ believe that _static_ checks could prevent problems arising from _unexpected_ conditions in the _data_? -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting Paul Rubin <"http://phr.cx"@NOSPAM.invalid>: > Luis Zarrabeitia writes: > > Wait, do you _really_ believe that _static_ checks could prevent problems > > arising from _unexpected_ conditions in the _data_? > > The data does not arrive from outer space on a magtape stapled to a > meteor. It comes out of another program. Most of the problems in > processing it come from mismatches between the processing programs and > the generation programs. Static checks would help eliminate those > mismatches. No, copy and paste from the original data structures would eliminate those mismatches. A compiler checking the reimplementation of said data structres, whatever the language, has no way of knowing if the structure matches. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 15, 12:21 pm, Bruno Desthuilliers > wrote: > > > Once again, the important point is that there's a *clear* distinction > > between interface and implementation, and that you *shouldn't* mess with > > implementation. > > If you "*shouldn't* mess with the implementation", then what is wrong > with enforcing that "shouldn't" in the language itself? Because, as a library user, it should be my power to chose when and how I _should_ mess with the implementation, not the compiler, and definitely not you. > So let's take the airplane example. Boeing and its contractors > probably has hundreds of programmers working on millions of lines of > code. If they believed you, they would abandon enforced data hiding, > and programmers would have much more discretion to screw around with > code that they don't work on directly. An FMS programmer could perhaps > decide to change the parameters of the engine controls, for example. I really hope that, at Boeing, they do a lot of unit tests and code reviews before the code is commited. Messing with the internals wouldn't be the only bad thing that could happen, you know... And I'd say that "x._private" where x is not 'self', would be very easy to catch on those code reviews. And, as someone else pointed out, even with 'strong' enforcement of data-hiding, you can usually access the privates anyway - it's just a bit harder to do, and a lot harder to discover. You pointed out previously that Python wasn't up to the task of running untrusted code on my own application, and I agreed. _That_ is what you seem need, and enforced data hiding does very little towards it. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 19, 7:13 am, Bruno Desthuilliers [email protected]> wrote: > > > I must be missing the point : if it's a public attribute, it doesn't > > need a "property" ? I guess we use the same words for different things > here. > > Yes, you are missing more than one point. > > Scala automatically converts public data members into properties, > apparently to save the programmer the trouble of doing it manually. If > you are interested, I'm sure you can find publicly available > information on it. Russ, I think _you_ are missing the point. If the attribute is already public, why does it need properties? Why would a programmer go to the trouble of adding them manually, just to get one level of indirection for an already public attribute? > > I definitively wouldn't bet my ass on language-level access restriction > > to protect software from fraud or sabotage. > > You're missing the point here too. I'll try one more time to explain > it. And I think you are conflating the idea of "private" as in "secret information that should not be known by the _public_" and "private" as in "static safeguards enforced by the compiler to prevent accidents" [and you are missing the third, "compiler feature to prevent namespace pollution without having to use extremely unlikely variable names", i.e, self.__x in python]. No wonder you can't get Bruno's point. For the second, static checks to prevent accidents, you have pylint. For the first, not only you are using the wrong tool, but you are barking at python for not having it. Assuming that pylint is perfect (big assumption, but it is up to you to prove where it fails), what would be the difference between only accepting/running "pylint-authorized code" and the enforced hiding you desire? This thread is starting to remind me of a professor of mine, who once claimed that python didn't have private attributes because it "is opensource and anyone can see the source code anyway", and the obvious confusion of his students ("why should I make my entrypoint '_public_ static void main', if it is _my_ sourcecode and I don't want to share it?"). What you want is not enforced data hiding. You want something actually designed to try to prevent abuses from hostile programmers - go use .Net or Java, who attempt to do that (I don't know with what level of success, but they at least provide you the 'locks' and 'police' that you need). Or better yet, write a proposal about how to implement code trust in Python. I'll support you on that one, and I think many others will. But if you keep presenting data hiding as a solution to that problem... I doubt that you will be heard. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." :
> One of the main benefits of properties is that they allow you to more
> safely put attributes in the public interface. If you later decide
> that the attribute shouldn't have been in the public interface, you
> can convert it to a property and make it do whatever you want it to
> do. That won't always save you, but sometimes it can.
That's true in Java, and python pre-'descriptor protocol'.
It boggles me when I see python code with properties that only set and get the
attribute, or even worse, getters and setters for that purpose. In my university
they teach the students to write properties for the attributes in C# ("never
make a public attribute, always write a public property that just gets and sets
it"). I never understood that practice either, given that the syntax for
attribute access and property access in C# is exactly the same. (Could it be
that even if the syntax is the same, the compiled code differs? Don't know
enough about .NET to answer that).
I think I'm getting offtopic now. I better leave :D
[snip the rest of the email, as I agree with it]
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 19, 6:24 pm, "James Mills" > wrote: > > > Python programmers tend to not have a need for > > properties. Quite honestly they are a waste of time. > > They come from traditional OO approaches to software design > > (and mostly from the Java world). > > With statements like that, it's no wonder you don't understand the > value of encapsulation. > [snip] > > If you didn't plan ahead and encapsulate the radius from the start, > properties allow you to save yourself and encapsulate it later without > breaking the client's code. Python programmers don't _need_ to plan ahead and encapsulate the radius from the start. That's the whole point. No clairvoyance needed. I kind of like that. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting Luis Zarrabeitia : > > Quoting "Russ P." : > > > On Jan 19, 6:24 pm, "James Mills" > > wrote: > > > > > Python programmers tend to not have a need for > > > properties. Quite honestly they are a waste of time. > > > They come from traditional OO approaches to software design > > > (and mostly from the Java world). > > > > With statements like that, it's no wonder you don't understand the > > value of encapsulation. > > > [snip] > > > > If you didn't plan ahead and encapsulate the radius from the start, > > properties allow you to save yourself and encapsulate it later without > > breaking the client's code. > > Python programmers don't _need_ to plan ahead and encapsulate the radius > from > the start. That's the whole point. No clairvoyance needed. I kind of like > that. Oops. I didn't noticed we were agreeing on this last point. Bad english... bad... [btw, I highly doubt James doesn't understand the value of encapsulation. Don't you mean "enforced data hiding" again?] Cya! -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 19, 7:44 pm, wrote: > > [removing david's message] > > > Why did you email your post to me? Did you really think I wanted to > see it in my inbox? I assure you I did not. Don't get mad at him... and don't take it personal. The reply-to header of this mailing list (usenet users: for some of us, this is only a mailing list, and can't hope for more) points to the sender, and not the list. Many believe it is the right thing to do, but if your mailer doesn't have a 'reply to list' function, like the one I'm using right now (Horde/Imp), your only option is to reply-to-all and then delete the original sender. I can't blame anyone for forgetting about the last part. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 19, 5:09 pm, Luis Zarrabeitia wrote: > > > Russ, I think _you_ are missing the point. > > If the attribute is already public, why does it need properties? Why would > a > > programmer go to the trouble of adding them manually, just to get one level > of > > indirection for an already public attribute? > > You don't understand the purpose of properties -- and you tell me that > *I* am the one missing the point? This line would make a lot more sense if you were talking about Java's getters and setters, or about a language where accessing a property is different than accessing an attribute (which would make little sense). If properties already let you change from attribute to method without affecting the caller, why do you need a property that does nothing? -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > In the circle example, properties are nice for guaranteeing > consistency between the radius and the area, but they are not of much > use if you decide later that the client should not be allowed to > change either one. Well... I suppose you could define the setter to do > nothing ... but you had better figure a way to notify the client about > it. Well, you could make it raise an exception. There was one C#1.0 class that did this, Liskov substitution principle be damned (it was for a subtype). Very frustrating. Once you decide for a public interface, you shouldn't change it... But, if you absolutely have to do it, complain loudly and as soon as possible. In python, I'd say that [a subclass of?] AttributeError would be the best solution for this ill-advised situation. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting Paul Rubin <"http://phr.cx"@NOSPAM.invalid>: > Luis Zarrabeitia writes: > > > Luis Zarrabeitia writes: > > class ImmutableType(type): ... > > Thanks for posting this, I haven't replied because I bookmarked the > post for later study, but that was several days ago, so I just wanted > to say that I'm still looking at it. It's an area of Python that I've > somewhat purposely stayed away from. Hehe. Keep away - once you get dive into it, it'll be hard go get out. It's really addictive :D > > I use them, a lot, specially when writing decorators... Many times I > > just want to 'mark' the decorated functions so I can inspect those > > marks later. I'd rather have a semi-private namespace for each pair > > ([group of]calling function[s], object), > > Right, thus the usefulness of a static tool that can find all those > places where extra attributes are created. Basically I can see three > approaches to this question: Btw, this thread inspired me to do another proof-of-concept stuff that I may be using more seriously. Too bad I don't have anywhere to upload it right now... Anyway, it looks like this: suppose I need to attach some attributes to the object "x", but I don't want to do x.attr import namespaces # my module class my_private_namespace(namespaces.Namespace): pass def this_function_stores_the_attr(x): ns = my_private_namespace(x) ns.attr = 5 # I'm creating an attribute on the fly # but at least I'm not touching x. def this_function_reads_the_attr(x): ns = my_private_namespace(x) print ns.attr > 1) Program in a style where you create and modify attributes all over > the place willy-nilly, with no controls whatsoever, either automatic > or stylistic. From experience (it is a common style in Javascript) I > can say this is a big mess and I think no experienced Python > programmers recommend it. Indeed. Though I don't consider myself 'experienced', I certainly don't recommend it. > 2) Have mandatory encapsulation like Java's, no way to escape. Bruno > and yourself vehemently object to this, Russ P seems to want it, my > view is that it's not in the Python spirit, so I can accept the > argument that those who really want this are better off choosing > another language. Btw, I noticed a funny side effect of my 'namespaces' module (needs a LOT of work, this was the first time I touched weak references. I should find some place to upload the module): = import namespaces class public(namespaces.Namespace): pass class private(namespaces.Namespace): # the initializer could check if pass # its called from outside the class. Performance penalty. class A(object): """dummy class A, with one 'private' attribute x, and one normal 'attribute' x.""" def __init__(self): self.x = id(self) # normal attr pub = public(self) pub.f = self.f priv = private(self) priv.x = "this is the private" def f(self): print "normal x: ", self.x priv = private(self) print "private x: ", priv.x >>> a = A() >>> dir(a) ['__class__', , 'f', 'x'] >> a.f() normal x: 147956684 private x: this is the private >>> p = public(a) >>> dir(p) # Look, there is no 'x' attribute! ['__class__', , 'f'] >>> p.f() # but f still works! normal x: 147956684 private x: this is the private == Of course, without checks in 'private', one could say priv = private(a); priv.x, but the most interesting part, for me at least, was the ability to define a 'public' interface for a, that contains no attribute directly referencing the object 'a' with its internals - only the names explicitly declared on the 'interface'. Indirectly... well, p.f.im_self will return back the 'a' object. Bah, I'm ranting now. I just got carried away with my little experiment. Sorry. Ah, and yes, metaclasses are dangerously addictive :D > 3) Program in a style where creating new attributes outside the > initializer is normally avoided by convention, but it is possible and > sometimes desirable to break the convention. This seems reasonable > and Pythonic to me. But, any place I break the convention, I should > be able to say "I broke the convention here for such and such a > reason". And (this seems to be a bone of contention) IMO, it would be > good to be able to audit a large codebase with a tool like Pylint, to > automatically find all the places where such breakages occur. Right > now there seems to be no way to do that relia
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 19, 9:21 pm, Paul Rubin <http://[email protected]> wrote: > > Bruno Desthuilliers writes: > > > The failure was because a module tested, QA'd and certified within a > > > given context (in which it was ok to drop the builtin error handling) > > > was reused in a context where it was not ok. And the point is exactly > > > that : no *technology* can solve this kind of problem, because it is a > > > *human* problem (in that case, not taking time to repass the whole > > > specs / tests / QA process given context change). > > > > He says that "no *technology* can solve this kind of problem." > > First of all, I'm not sure that's true. I think technology *could* > have solved the problem -- e.g., Spark Ada, had it been properly > applied. But that's beside the point. The point is that the problem > had nothing to do with encapsulation. The rocket failed because a > conversion was attempted to a data type that could not hold the > required value. Am I missing something? I don't see what that has to > do with encapsulation. > > The logic seems to be as follows: > > 1. Ada enforces data hiding. > 2. Ada was used. > 2. A major failure occurred. > > Therefore: > > Enforced data hiding is useless. I don't think that was the logic... At least, it wasn't what I understood from the example. We were talking at the time (or rather, you both were, as I think I was still away from the thread) about QA versus static checks (as a superset of 'enforcement of data hiding'). Is not that those checks are useless, is that they make you believe you are safe. Granted, you may be safe-er, but it may be better to know beforehand "this is unsafe, I will check every assumption". The arianne 5 example cuts both ways: messing with "internals" (not that internal in this case, but still) without fully understanding the implications, and overly trusting the checks put in place by the language. I don't know spark-ada, but the only thing I can think of that would have prevented it is not purely technological. It would have been a better documentation, where that particular assumption was written down. A language can help you with it, perhaps spark-ada or eiffel or who-knows-what could've forced the original developers to write that piece of documentation and make the arianne 5 engineers notice it. So, Arianne 5's problem had nothing to do with _enforced data hiding_. (Why do you keep calling it 'encapsulation'?). It was a counterexample for your trust on compiler checks. Btw, what do you have against using pylint for detecting those 'access violations'? > If that reasoning is sound, think about what else is useless. I _hope_ that wasn't Bruno's reasoning. I don't want to switch sides on this discussion :D. Cheers, -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 20 January 2009 02:00:43 am Russ P. wrote: > On Jan 19, 10:33 pm, Luis Zarrabeitia wrote: > > (Why do you keep calling it 'encapsulation'?). > > I keep calling it encapsulation because that is a widely accepted, > albeit not universal, definition of encapsulation. [...] > Encapsulation conceals the functional details of a class from objects > that send messages to it. [..] > Definition: In Object Oriented Programming, encapsulation is an > attribute of object design. It means that all of the object's data is > contained and hidden in the object and access to it restricted to > members of that class. Ahh, 'concealed', 'contained', 'hidden'. Except the last one, "hidden", python does the rest... and one could argue the self.__privs get pretty well hidden. Not 'forbidden', 'restricted', 'enforced'. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 20 January 2009 05:00:34 am Paul Rubin wrote: > Luis Zarrabeitia writes: > > No wonder you can't get Bruno's point. For the second, static checks > > to prevent accidents, you have pylint. For the first, not only you > > are using the wrong tool, but you are barking at python for not > > having it. Assuming that pylint is perfect (big assumption, but it > > is up to you to prove where it fails), > > Whaat? Assuming a program is perfect unless a failure is proven > is not at all a sane approach to getting reliable software. It is > the person claiming perfection who has to prove the absence of failure. No, no. I meant that if pylint works as its specification says it would. Russ says (or seems to say, I don't know, I'm confused already) that it is not good enough, that what pylint says it does is not what he wants (otherwise, this subthread would have died a long time ago). So, assuming that pylint works as specified (its up to "you" to find out if it doesn't and file bugreports about it, just like you would do if you find out that the static-checker for your enforced-static-checks-language is buggy), what would be the difference between only accepting/running "pylint-authorized code" and the enforced hiding you desire? Sorry, I didn't realize that perfect was a too strong word for that. "I speaks english bad" :D Cya! -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 21 January 2009 02:30:54 am Russ P. wrote: > That could work. As long as it's well-engineered (not a hack), well- > supported (part of the standard library), and does the job, that's > probably all that matters. But you keep failing to explay why do you need it to be _part of the standard_ library (or whatever). If you need it in your project, _use_ it. If you don't, then don't use it. If _you_ need that thing you call security, just use it already and quit complaining that we don't use it. Is there a policy in your project that you can't use any external? -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 20 January 2009 09:52:01 pm Paul Rubin wrote: > Luis Zarrabeitia writes: > > > Whaat? Assuming a program is perfect unless a failure is proven > > > is not at all a sane approach to getting reliable software. It is > > > the person claiming perfection who has to prove the absence of failure. > > > > No, no. I meant that if pylint works as its specification says it would. > > Oh, I see. Well, that would be ok, except Pylint is not specified as > detecting the types of access that Russ is concerned with. It can't, > for example, flag uses of setattr that might affect a particular > class. That would take something a lot fancier. True. And I doubt that the C++ compiler will flag the pointers running wildly pointing to random memory addresses and accessing the data in there. I doubt that pointer will 'respect' the 'private' keyword. I also doubt that the C# or Java _compiler_ will prevent you from using reflection somehow to access that data. But somehow the discussion shifted from an optional requirement (giving you the chance to explicitly use 'from lock import unlock; o = unlock(obj)') to "it can't be done _ever_" (using setattr/getattr is as explicit as your analogous 'unlock' function). Btw, the correctness of a program (on a turing-complete language) cannot be statically proven. Ask Turing about it. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 21 January 2009 02:03:07 pm Paul Rubin wrote: > Luis Zarrabeitia writes: > > But somehow the discussion shifted from an optional requirement (giving > > you the chance to explicitly use 'from lock import unlock; o = > > unlock(obj)') to "it can't be done _ever_" (using setattr/getattr is as > > explicit as your analogous 'unlock' function). > > The idea was the lock would be on the class, not on instances of the > class. So setattr/getattr would work on instances of unlocked classes > but not locked ones. If you wanted an unlocked instance of a locked > class, you could do it by making an unlocked subclass. Well, then, go change pylint to do that. But don't try to force it on _me_: If I want to access an attribute for an object on my program (from wherever it came from), I don't want _you_ or anyone else saying "no, its private". Even better. Realize that you are trying to use a tool made for debugging, documenting, and catching some obvious errors (private/public) for "security". Go fix Bastion, that would be your best bet. It was yanked out of python because it was insecure, but if someone were to fix it, I'm sure the changes would be welcomed. And then, it would be my choice whether to let you lock your instances in _my_ program, and it would be yours to lock all of mine in yours (and way more). Btw, when I was programming in .Net (long time ago), I found a little library that I wanted to use. The catch: it wasn't opensource, it had a gratis version, and a full, payed version... The difference? The full one had some attributes public that were private on the free one. Well, I didn't wanted code on my app from someone who didn't know the meaning of the 'private' keyword anyway. You (well, Russ more than you) almost seem to be trying something like that. > > Btw, the correctness of a program (on a turing-complete language) cannot > > be statically proven. Ask Turing about it. > > That's an irrelevant red herring, True, my bad. But I don't think it is _fully_ irrelevant. See, a thread that begun with saying that a piece of code was hard to read has evolved to changing the language so we could have tools to statically proving "certain things" with the code. And each time a "suggestion" appears (from people that, at least at the time of suggesting it, were genuinely interested on helping) that doesn't fulfill your [plural, including russ] goal of having static typing and data hiding in the official python, you shoot it down because some other "it cannot be proven statically" reason. Sure, it is always a very well defined "certain" thing and not correctness in general, but that "certain" thing changes as soon as a suggestion is made to amend it. I'm obviously growing tired of that pattern. Have pylint check if someone uses getattr in your code, at all. If pylint doesn't do it, just grep for it and don't run that code. Simple. Btw, this may put and end to this discussion: import gc gc.get_objects() No amount of metaclasses, pylints, decorator, etc, will stop someone from using that to get access to _all_ objects of the program. If you need to keep a secret, don't put it on the same memory space that the untrusted code in python (actually, don't do it on any language). If you need static proofs, use a less dynamic subset of python, and use or develop tools to check if you tried to get out, ever (because if you get out once, you will not be able to track the results). Or, don't use python. (and certainly don't use C++, for that matter, even if C++ has a 'private' keyword). -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Wednesday 21 January 2009 04:16:38 pm Russ P. wrote: > On Jan 21, 9:34 am, Luis Zarrabeitia wrote: > > But you keep failing to explay why do you need it to be _part of the > > standard_ library (or whatever). > > Technically, it doesn't need to be. But if someone proposes using > particular language for a major safety-critical project, the critical > features realistically need to be part of the standard language or at > the very least in the standard library. I assume, then, that no safety-critical project uses any external tool for checking anything important. > The requirements are different for government-regulated code than they > are for non-critical commercial code, as well they should be. Imagine > trying to explain to the FAA that you are going to use a language that > is inappropriate by itself for a safety-critical system but will be > appropriate with the addition of third-party software. That just won't > fly. Then it wont fly, period. If you start explaining that the language is inappropriate, then you've already made the case. I would argue that the language _is_ appropriate _because_ all your concerns can be solved. (assuming, of course, that the theoretically-solvable concerns are can actually be solved). But as you haven't stated yet any specific concern other than silly locked-doors analogy and "you are crazy if you think that a nuclear blahblah don't use private variables", this is kind of pointless. > Then again, the FAA might not approve Python for flight-critical or > safety-critical code even if it gets enforced data hiding, so perhaps > the point is moot. Most likely. For what you've said, if the use of an external tool would make it inappropriate, I highly doubt that they'll like an informally-developed community-driven open source language who's developers and a good portion of its community consider silly the idea of using enforced data-hiding for anything other than debugging. > > If you need it in your project, _use_ it. If you don't, then don't use > > it. If _you_ need that thing you call security, just use it already and > > quit complaining that we don't use it. Is there a policy in your project > > that you can't use any external? > > I don't recall complaining that anyone doesn't use something. Well, you want it on the python compiler I use. That seems awfully close. Funny thing... if pylint became part of the standard library, I may welcome the change. I certainly wouldn't be complaining about it unless it was enabled-by-default-and-can't-disable-it. > In fact, > in the unlikely event that enforced data hiding is ever added to > Python, nobody would be forced to use it (except perhaps by your > boss or your customer, but that's another matter). No one is now. And no one is forced to not use it either (except perhaps by your boss or your customer, but that's another matter). -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Thursday 22 January 2009 08:32:51 am Steven D'Aprano wrote: > And now I have accidentally broken the spam() method, due to a name clash. True, that's bad. I wish that were 'fixed'. > Besides, double-underscore names are a PITA to work with: Isn't that example the point of having self.__private variables? To make sure that the Parrot.__private attributes don't clash with the RedParrot.__private attributes with the same name? [parrot example follows just for context, but my reply ends here] > >>> class Parrot(object): > > ... __colour = 'blue' > ... def __str__(self): > ... return 'A %s parrot' % self.__colour > ... __repr__ = __str__ > ... > > >>> class RedParrot(Parrot): # Just like Parrot, only red. > > ... __colour = 'red' > ... > > >>> Parrot() > > A blue parrot > > >>> RedParrot() > > A blue parrot -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Friday 23 January 2009 06:31:50 am Antoon Pardon wrote: > On 2009-01-16, Luis Zarrabeitia wrote: > > Quoting "Russ P." : > >> If you "*shouldn't* mess with the implementation", then what is wrong > >> with enforcing that "shouldn't" in the language itself? > > > > Because, as a library user, it should be my power to chose when and how I > > _should_ mess with the implementation, not the compiler, and definitely > > not you. > > Why should it be in your power? By messing with the implementation of a > library you risk the correctness of the code of all participant coders in > that project. I not that sure it should be your power to chose when and how > to do that. Ok, let me fix that. It should be in _our_ power as the team of all participant coders on _our_ project to decide if we should mess with the internals or not. What makes no sense is that it should be in the original author's power to decide, if he is not part of _our_ team. Do you like it better now? Wasn't it obvious in the first place? -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting Steven D'Aprano : > On Fri, 23 Jan 2009 13:07:55 -0500, Luis Zarrabeitia wrote: > > > It should be in _our_ power as the team of all participant coders on > > _our_ project to decide if we should mess with the internals or not. > > > > What makes no sense is that it should be in the original author's power > > to decide, if he is not part of _our_ team. > > Makes *no* sense? There's *no* good reason *at all* for the original > author to hide or protect internals? My bad, sorry. It makes sense... if the original author is an egotist who believes he must control how I use that library. Or, if external forces make him do it (maybe like, 'oh, if I change python, then I'm not using python anymore'). > Let's be specific here. The list implementation in CPython is an array > with a hidden field storing the current length. If this hidden field was > exposed to Python code, you could set it to a value much larger than the > actual size of the array and cause buffer overflows, and random Python > code could cause core dumps (and possibly even security exploits). In which case, my code would be broken. (Wait, let me be clear: in which case, our team's code may be broken - but it was _our_ team's decision, knowing the risk). If a variable is marked as... I don't like 'private', I'll call it 'implementation detail', I would not use it without good reason. Not even by subclassing it. Why do you assume that I'd change list._length if I could? I wouldn't. Anyway, did you notice that your "counter-example" was a radical change-the-way-python-works scenario? I also don't want to change the interpreter's code on the fly. Now, if you take that as a confession that I really, really, want enforced data hiding and that everything I've said is plain wrong, so be it. After all, I treat python's interpreter as a black box, don't I? > So what you're saying is that the fundamental design of Python -- to be a > high-level language that manages memory for you while avoiding common > programming errors such as buffer overflows -- makes "no sense". Is that > what you intended? Yes, that's what I intended, obviously. I'd like to have buffer overflows in python. In case you don't understand irony: don't go putting words in my mouth. I'm not putting words in yours. > As I see it, you have two coherent positions. On the one hand, you could > be like Mark Wooding, and say that Yes you want to risk buffer overflows > by messing with the internals -- in which case I'm not sure what you see > in Python, which protects so many internals from you. Or you can say that > you made a mistake, that there are *some* good reasons to protect/hide > internals from external access. Or, I could have a third option: assume that I am a grownup who knows what he is doing. After all, even with all those "protections" in list, I could just create an extension module to shoot me in the foot anyway, if I really wanted to. > In the second case, the next question is, why should it only be code > written in C that is allowed that protection? Bug? Not worth the effort of exposing those variables? I don't know... [Btw, do you realize that C++'s private also don't provide that protection? I have almost no experience with C++ and found it trivial to circumvent] I don't think this is going anywhere. Now you are trying to push me to the extremes, changing what I _said_ for your exaggerated interpretation of it just so you could shoot it down, or force me to say that I want buffer overflows in python. I believe that's called "strawman". I stand by my words - but not by your "interpretation" of them: > > What makes no sense is that it should be in the original author's power > > to decide, if he is not part of _our_ team. Do you _really_ read from that sentence that I should dislike python because it makes it a bit harder to get a buffer overflow with their native types? -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 23, 6:36 pm, Luis Zarrabeitia wrote: > > > > Makes *no* sense? There's *no* good reason *at all* for the original > > > author to hide or protect internals? > > > > My bad, sorry. > > It makes sense... if the original author is an egotist who believes he > must > > control how I use that library. > > If the original author provides you with the source code and the right > to modify it, he cannot possibly control how you use the library. You > can trivially disable any access controls. But for some reason that's > not enough for you. No, I'm not satisfied with forking python just to use sys._getframe. > Has it occurred to you that some users might actually *want* access > controls? Maybe some users want to actually use the library as the > author intended it to be used. What a bizarre concept! Huh? Then... use it as the author intended. I am _not_ forcing you to use the obj._protected attributes! Even I run pylint against third party libraries just to assess if the risk of them messing with someone else's internals is worth taking (as in the case of inspect.currentframe, which is exactly the same as sys._getframe) or not (random library downloaded from the net). > Oh, but only a paranoid fool could possibly want access controls, eh? > Who's the egotist here? See? You too changed what I said. Somehow you managed to delete the _other_ situation I gave. Not worth correcting it. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting Steven D'Aprano : > On Fri, 23 Jan 2009 21:36:59 -0500, Luis Zarrabeitia wrote: > > > Quoting Steven D'Aprano : > >> Makes *no* sense? There's *no* good reason *at all* for the original > >> author to hide or protect internals? > > > > My bad, sorry. > > It makes sense... if the original author is an egotist who believes he > > must control how I use that library. > > Then I guess Guido must be such an egotist, because there's plenty of > internals in Python that you can't (easy) mess with. Yeap, ignore the second part, and claim that I only said this. > > Or, if external forces make him do > > it (maybe like, 'oh, if I change python, then I'm not using python > > anymore'). > > That parenthesised comment makes no sense to me. It was directly countering your 'list' example. _I_ don't want to change _python_, nor python's assumptions and assurances. A standard python that can segfault would be no python. Again, if you think that means that deep down I like enforced data hiding, so be it. > [...] > > If a variable is marked as... I don't like 'private', I'll call it > > 'implementation detail', I would not use it without good reason. Not > > even by subclassing it. Why do you assume that I'd change list._length > > if I could? I wouldn't. > > I didn't say you would change it on a whim. I said that *if* it were > exposed to Python code, you *could* change it. You might change it > because you thought you had a good reason to. You might change it by > accident. You might not realise the consequences of changing it. Who > knows? It doesn't matter what your motives are. Exactly, they don't matter to you, unless you happen to be running my code. > My point is that you claimed that there is no good reason at all for > hiding implementation details. Python is full of implementation details > which are quite effectively hidden from Python programmers. So there are > two possibilities: I didn't say "at all". Those were your words, not mine. I said that it makes no sense that the power lies on _you_ instead of on _my team_. And, when I said that, I recall we were talking about the python language, not C. > (1) you are right that it "makes no sense" (your words) for the original > author (in this case, Guido) to hide those implementation details from > Python programmers; or Just to be clear: I think the opposite. He made a language and interpreter, and it ensures that it will not segfault because of incorrect pure python code. That is my blackbox. In doing that, he made a language where I don't have to worry that much about enforcing access restrictions. Again, if you think that means that I want enforced data hiding in python, so be it. > (2) you are wrong that it "makes no sense", because there is at least one > case where the original author (Guido again) did a sensible thing by > hiding implementation details. hiding the implementation details of a C implementation... not python. > In an effort to avoid going round and round in circles, let me explicitly > say that option (2) does not imply that it always makes sense to hide > implementation details. Huh? It makes sense to hide implementations details. I'd say it always makes sense. What doesn't make sense is that someone fights so vehemently to stop me from getting at them, on my code, on my systems. > [...] > >> So what you're saying is that the fundamental design of Python -- to be > >> a high-level language that manages memory for you while avoiding > >> common programming errors such as buffer overflows -- makes "no sense". > >> Is that what you intended? > > > > Yes, that's what I intended, obviously. I'd like to have buffer > > overflows in python. In case you don't understand irony: don't go > > putting words in my mouth. I'm not putting words in yours. > > And neither am I. I'm pointing out the logical implications of your > position. If you find those implications unpleasant, then perhaps you > should modify your position to be less extreme and more realistic. But it is realistic. You put the words "at all", and you shifted the discussion from Python to C, and from programs in python to python's implementation. [snip the comments about the advantages of data hiding. We are not talking about data hiding, we are talking about having data hiding enforced against me] > > I stand by my words - but not by your "interpretation" of them: > > > >> > What makes no sense is that it should be in the original author
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > Once again, if you have the source code for the library (and the right > to modify it), how does the "power" lie with the library implementer > rather than you the user? > > You say you don't want to "fork" the library. Let's stipulate for the > sake of argument that a one-line change is indeed a "fork." It is. For starters, I'd lose the information of "this attribute was intended to be internal and I'm accessing it anyway". > Think > about what you are saying. You are saying that you should dictate how > the producer of the library should implement it because you don't want > to be bothered to "fork" it. No. I am not dictating _anything_. The beauty of it, you don't have to do _anything_ for this to happen. Now, you may say that I'm trying to force you to relax and do nothing instead of complaining because the language I use doesn't put enough restrictions on me. > If you don't like his design decisions, > shouldn't the onus be on *you* to make the trivial change necessary to > get access to what you want? Or contacting him about it and maybe send him a patch, sure, why not. But this has nothing to do with enforced data hiding. Having obj._public_var is just as badly designed as having "private public_var". > Imagine a person who repairs computers. He is really annoyed that he > constantly has to remove the cover to get at the guts of the computer. > So he insists that computers cases should be made without covers. > After all, manufacturers put covers on computers only because they > don't trust us and think we're too "stupid" to safely handle an > uncovered computer box. > > That is logically equivalent to your position on enforced access > restrictions in software. Do you realize that most computer cases are trivially easy to open? (Nevermind that there are other reasons... dust, protection against physical damage, etc. My PC is locked enough to protect them, but opened enough so I can "play" with it whenever I need) > > And, FYI, when programming in java, C++ or C#, I do use "private" and > > "protected" variables, not becasue I want to forbid others from using it, > but > > because it is [rightly?] assumed that everything marked as public is safe > to use > > - and I consider that a strong enough "external" reason to do it. > > You could just use leading underscores and note their meaning in the > documentation. If that's such a great approach, why not do it? Yes, I > know, it's not a widely used convention in those other languages. Fair > enough. It is not a widely used convention, and that is reason enough for me. It's quite a contradiction to say in the code "this thing is safe to use" and then document it as "highly unsafe - do not touch". With Java and C# I'm more lenient (and work more with explicit interfaces rather than just the public/protected/private thing). BTW, the actual 'private' case for most languages is a different beast: it is used to prevent namespace pollution/name clashes. I can't easily simulate those with public attributes in C#/Java/C++ (but I concede that their 'privates' do a better job at this than python's self.__local) > But you could still do it if it's such a good idea. I think someone commented in this thread about a case where he had to do exactly that. [copying from your other reply] > But what if I want an automatic check to verify that I am using it as > the author intended? Is that unreasonable? Think of enforced access > restriction as an automatic "assert" every time an attribute is > accessed that it is not a private attribute. I think that was a reply to a message where I said that I used pylint run those checks on third party libraries. And I obviously can do the same with my own code. I don't have threading now, so I can't check if I really said that. If I didn't, well, I'm saying it now. Now, as Paul Robin pointed out, those statics checks done by pylint can't catch a runtime workaround using eval, exec or getattr/setattr. But neither can C++. By the way, I urge you to try to write code that pylint doesn't complain about. It's easy to not be satisfied with the checks it provides if you haven't used it. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
Quoting "Russ P." : > On Jan 24, 9:54 pm, Luis Zarrabeitia wrote: > > Quoting "Russ P." : > > > > It is. For starters, I'd lose the information of "this attribute was > intended to > > be internal and I'm accessing it anyway". > > Not really. When you get a new version of the library and try to use > it, you will quickly get a reminder about the change (assuming your > tests provide sufficient converage, and also assuming that the > attribute is not made public in the new version). So you don't really > even need to keep track of the change. See? With every new version that doesn't change the behaviour, I have to modify the source just to see if the tests run. That _is_ a fork. And that's assuming the bright case where I have the source. > > No. I am not dictating _anything_. The beauty of it, you don't have to do > > _anything_ for this to happen. > > You are trying to dictate that the library implementer not be allowed > to use enforced access restriction. And, in the larger sense, you are > trying to dictate that access restrictions not be enforced in Python. Now, please, explain to me, why are you so interested on preventing me from using the internals on my computer? If you want controls in the code that runs on your system, you can. > > Or contacting him about it and maybe send him a patch, sure, why not. But > this > > has nothing to do with enforced data hiding. Having obj._public_var is just > as > > badly designed as having "private public_var". > > Sure, go ahead and contact him. If he agrees that a private attribute > should be public, then the problem is solved. But if he does not > agree, he should not be forced to bend to your desire. Wait, if I change my project to ignore the data hiding (enforced or not), am I forcing the author to bend for my desire? Please explain your reasoning. Or better yet... don't. I will just give up, right now. This is no longer about "security", "good practices", "software engineering", "bug catching" or "formal proofs" as you've tried to paint it before. This is about you wanting to control how others use your code. And while it may be your legal right, that isn't the discussion I thought I was getting into. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 27 January 2009 04:39:02 am Bruno Desthuilliers wrote: > Still not. But it's interesting to note that you consider everyone > disagreeing with you as basically the same person. Hehe. At the beginning of this thread, I also thought that Russ P. and Paul Robin were the same person. I have serious problems with names. [My apologies to both of you, if I said something that made you notice my confusion]. P.S: Just to be clear, I'm neither Russ P. nor Paul Robin :D -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 27 January 2009 02:13:50 pm Russ P. wrote: > I suggested that maybe -- maybe! -- the versatility of Python could be > enhanced with enforced data hiding. I was careful to say several times > that I don't know if that can even be done in Python (with all its > introspection and so forth). And it would always be optional, of > course (as far as I know, no language forces anyone to declare > anything private). I think you still fail to see that what we are objecting is not that the original writer can "optionally" use the enforced data hiding (which, as someone pointed out before me, can be done with tools like pylint). The objection is about the _user_ of the library. If you don't force it into the _user_, how is it different from the current situation? And if you do force it, how can you say that it is optional? -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of "Readability counts"?
On Tuesday 27 January 2009 02:56:51 pm Russ P. wrote: > On Jan 27, 11:40 am, Luis Zarrabeitia wrote: > > I think you still fail to see that what we are objecting is not that the > > original writer can "optionally" use the enforced data hiding (which, as > > someone pointed out before me, can be done with tools like pylint). The > > objection is about the _user_ of the library. If you don't force it into > > the _user_, how is it different from the current situation? And if you do > > force it, how can you say that it is optional? > > As I have pointed out several times, the user cannot be forced to > respect data hiding if he has access to the source code (and the right > to modify it). If Python had a "private" keyword (or equivalent), for > example, the user would only need to delete it wherever necessary to > gain the desired access. And, as others and I have pointed out several times, that would mean to maintain a fork. Would you say that current C++ has "optional" enforced data hiding for the user? After all, you can just fork the module (and if you don't have the source, you could mess with pointers until you find it). Also, I once pointed out that "access to the source code and right to modify it" is not a given. What you are proposing is not optional at all. You want the power to control what others do - and while it may be your legal right, it's also everyone else's right not go our of our ways to help you have it. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Quoting [email protected]: > > Or ``#define private public`` before including the header files. Which > > doesn't look complicated to me. > > Which again won't always work, if: > > (a) the header defines another macro, say, "PRIVATE", as "private", > and uses PRIVATE to declare private members [other reasons deleted] So, can I assume that most of the C++ code out there defines "PRIVATE" as "private" just to prevent breaking the encapsulation _intentionally_? Somehow I find that hard to believe. > Anyway, it doesn't matter. We're losing the point here. The point is > that language support for private access, by disallowing user access > to private data, provides an unambiguous information hiding mechanism > which encourages encapsulation. And Python, by providing a well defined convention of what is inaccessible, provides an unambiguous information hiding mechanism wich encourages encapsulation. > Python's approach, however, which is > only a naming convention rather than a language feature, merely TRUSTS > the programmer not to break encapsulation. And sure, if we're all good > programmers, everything will go well and we'll end up with an > organized application. But the danger is still there: at any given > time, we COULD break encapsulation! And what's the problem with that, exactly? I can break encapsulation... and I can jump off my roof. Why do _you_ care about what _I_ can do, as long as it doesn't harm _you_ (or others)? If you are worried about you breaking encapsulation, then just don't do it. It is not hard. Whenever you find yourself typing "._somehting", just check that the string before the dot is "self". If you can't trust yourself to access only the well identified "public" attributes, how can you trust that you will just not make "public" a private attribute anyway? -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
On Sunday 01 February 2009 08:00:18 pm Steven D'Aprano wrote: > On Sun, 01 Feb 2009 12:31:27 -0500, Steve Holden wrote: > Except of course it isn't. Nobody sensibly complains that they can't > mangle the length of a list, or move keys around inside dicts, or > whatever. This data hiding is a good thing. If lists and dictionaries were not C types, and python didn't have to shield us from the mess that is C and its pointers, that enforcement may not be such a good thing. And, while we are at it, that is not python having "selective" enforcement of data hiding but only for C, that's C/C++ having data hiding and not exporting the attributes back to python. > All I want is the ability to do with Python classes what I can do with C > extension types. I don't think that's an *unreasonable* ask, even if it > is *unpractical* given the current design of Python. Well, then. Do you want dynamic checks? Go fix Bastion/rexec (that would be a _good_ thing, valuable for way more than data hiding). Or do you want static checks? In that case, you have it already. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
On Monday 02 February 2009 04:51:11 pm Russ P. wrote: > As I said before, as an aeronautical engineer I don't know if enforced > access restriction can be added to Python without compromising or > unduly complicating the language. Maybe it can't. If that's the case, > then people should make that argument. But just saying that enforced > access restriction is useless in general is nonsense. Are we supposed > to believe that the designers of C++, Java, Ada, and Scala are all > idiots? I'm amazed at how quickly this thread degenerated into another 'enforced data hiding' thread. I think the previous one ran long enough for me to actually say that 'access restriction is nonsense', when my point had been '_enforced_ access restrictions in python is worthless in all the examples provided so far' (except perhaps the extensions modules, but those are not python). You are an aeronautical engineer. You, and I understand that, don't want, shouldn't want, and will not want to run anything you cannot trust. You want the most assurances you can get. You are well within your right to want that - to disallow in your systems, and in the systems that you build, anything that you even suspect that may threaten the integrity of the system, and let's face it, breaking the encapsulation, intentional or not, is pretty suspicious. So, in current python, _you_ have the _choice_ of preventing it. As the checks are static, of course, you can break them in runtime, just like you would in C, C++ and Java. But somehow, it is not enough for you that you have the choice, because that also gives _me_ the choice of _not_ doing it in my own systems. And you still haven't said why it bothers you that I have the choice. Now, if you were arguing for [truly optional - as in, the user decides] dynamic checks, you may see a very different position. That RExec and Bastion even existed should tell you that there is interest on implementing some kind of trusted execution (as in 'I trust this code to do whatever it wants, but not this other code'). That both projects failed should tell you that either it is impossible to achieve in python (which would be bad), or that there is just not enough interest on keeping them (which would not amaze me). But, if you are arguing for dynamic checks, those are not present in C++ either, and thus, it isn't really what you mean with enforced data hiding. > If an assignment to the previously > "private" attribute is missed, no warning will be issued (because > Python allows new attributes to be added anywhere, even completely > outside the class definition itself). And if the library is widely > used, the probability of such bugs occurring is very high. Good coding standards would prevent that. And by good coding standards, I mean "treat pylint and similar tools as a requirement before executing any code", and it will catch that sort of bugs. Again, _you_ have the choice. Use it if you wish. Now, I'm with you in that accidental variable creation is a nasty side effect of python dynamism (and that you may be forfeiting it if you go the pylint route). But that particular complaint has nothing to do with enforced vs not-enforced data hiding, and everything to do with static typing. And mind you, must of us who use python, do so _because_ of the dynamism and not in spite of it. Funny thing is, you have the choice, _now, today_, of having your precious static checks, both of them, for your projects. But you keep complaining because I also have the choice, and I may chose not to have them. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Quoting "Russ P." : > I know ... changing one word constitutes a "fork." Yeah, right. Yeah, right. > You can't be bothered to change one word, but the library developer should > be required to litter his code with leading underscores everywhere, No, instead they will have to litter his code with "private" keywords. (So now this is about laziness and not wanting to type "_"? The argument gets weirder and weirder) > and large development teams should depend on labor intensive code > reviews for checks that could be automated by the language. Or, by already existing third party tools that you insist on ignoring. > (And, please ... I am not suggesting that enforced access restrictions > would render code reviews unnecessary, but it could certainly simplify > them.) Please, tell, how does it having the checks on the interpreter will simplify them more than having the checks on an external tool? -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Quoting "Russ P." : > > Indeed he can. He can even do that in Python; it just requires a little > > self-discipline from the team, or a validation script on the code > > repository if he really doesn't trust them. Not only can this be done > > without forcing the rest of the world to play, it makes things a little > > less daunting when those nice clean interfaces turn out to be > > incomplete/too slow/not what you thought. > > This has already been refuted several times on this thread alone, so I > will not bother doing it again. > Please, point out where, because I don't recall you explaining why is not enough to use a "validation script" on the code if you wish to. I _do_ recall you saying that you didn't want the validation script unless it is integrated with python, but I'm yet to see the difference. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Quoting "Russ P." : > Imagine you own a company, and you decide to lease an office building. > Would you expect the office doors to have locks on them? Oh, you > would? Why? You mean you don't "trust" your co-workers? What are locks > but enforced access restriction? This analogy is nonsense. There is no way you will execute code on my system if I don't authorize it, regardless of how "public" are the variables declared in my code. No one will execute code on _your_ system either, without your authorization. That puts you in a different position: you can easily _check_ that everything is alright before executing, whereas in the office example, it cannot be done. Of course, if the analogy is flawed in such an essential aspect, I won't even humor it. I worry, though, that you obviously believe that it is not flawed. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
On Wednesday 04 February 2009 10:53:54 am Russ P. wrote: > On Feb 4, 5:35 am, Luis Zarrabeitia wrote: > > Quoting "Russ P." : > > This analogy is nonsense. There is no way you will execute code on my > > system if I don't authorize it, regardless of how "public" are the > > variables declared in my code. No one will execute code on _your_ system > > either, without your authorization. That puts you in a different > > position: you can easily _check_ that everything is alright before > > executing, whereas in the office example, it cannot be done. > > I don't follow your point, [...] > The locks on the doors are analogous to enforced access restrictions. And that is my point, nothing more, nothing less. They aren't analogous. I know a bit of python, and a bit of programming, and I think you do too. If you can't make your point without an analogy, isn't it perhaps that your point is not transferable from the analogy to the python context where you are trying to apply it?. You can control everything that happens in your systems, whatever those systems may be. There are no locks, no offices, no employees going unchecked. You can decide, at any time you want, if the code you are about to run meets your policies. The particular one you are talking about, the "data hiding", can be easily checked. By you, by the QA team, by a computer, by an automated system, by your own pseudo python interpreter that will run pylint against the code before trying to run it. Insert that into your office analogy, and maybe then situations will be a little more analogous. But keep in mind that the only difference between what you claim to want and what you currently have, is that _you_ (not me) can decide whether to use it or not. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Importing a file (not a module).
Is there any way to "import" a .py file that is not on sys.path?
I'd like to 'import' a file that resides somewhere on my filesystem without
having to add it's directory to sys.path. At first, I thought that something
like
my_module = __import__("path/to/file")
would work, but I was mistaken. Ideally, the path would be specified as a
relative path from the importer's module, and not from the CWD (that's another
question, I guess).
Related question: how could I change the sys.path for this_script.py without
changing it much? I'd like to have this_script a few more directories on its
pythonpath, but I don't want to clutter the begining of the script with
"sys.path.append(...)"s, specially because I need to do that for several
scripts. I thought of creating a modify_pythonpath.py and import it from all of
them, but I don't want to keep that script on the global python path nor on any
of the project folders (it is required by more than one).
Currently I have a symlink from the original modify_pythonpath.py to each
project directory, but that seems clumsy.
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list
PyGILState: The assertion 'autoInterpreterState' has failed
Hi, The project goal is to incorporate the functionality of interaction of the excel application (gnumeric) with the XO's journal. All the activities needs to register any change in that datastore (save and open files are made throw it). In order to apply this option, we need to call some python code from the implementation of the worksheet in C code. This is called embedded python in C. The steps followed to accomplish this goal came from the OLPC site recomendations, in wiki.laptop.org. The python script for the interaction with the journal's datastore can be found in here: http://wiki.laptop.org/go/Copy_to_and_from_the_Journal The changes in the gnumeric code are basically in the workbook-view.c and main-application.c to handle the open and save options. In the main- application.c the method gui_file_copy_from_journal uses the python api/c to make the call to the journal script. after this method and during the open of the file, an exception rises. Although we are not sure, we believe it has to do with the closure of the python enviroment after the finalize call. We need to erase this exception or may be just handle it. The error running in the XO is: gnumeric: Python/pystate.c:561 :PyGILState: The assertion 'autoInterpreterState' has failed The configuration of the XO where we are getting the exception is: Python 2.5 (r25:51908, Oct 19 2007, 09:47:40) [gcc 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Any help is greatly appreciated!!! Luis Orlando Carrión Rumiche Tata Consultancy Services Colonia 1329-Piso 3 Montevideo,. Uruguay Mailto: [EMAIL PROTECTED] Website: http://www.tcs.com Experience certainty. IT Services Business Solutions Outsourcing =-=-= Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: how to document a property
Quoting TP <[EMAIL PROTECTED]>: > d : > int(x[, base]) -> integer > > Convert a string or number to an integer, if possible. A floating point > argument will be truncated towards zero (this does not include a string > representation of a floating point number!) When converting a string, use > the optional base. It is an error to supply a base when converting a > non-string. If the argument is outside the integer range a long object > will be returned instead. > [...] > ### > > What is this default documentation? > Why? What you are reading is not the 'default documentation', but the documentation for the 'int' type. Do help(5) and watch the result. The problem is that when you do help(yourobj.d) you are not asking for the help of the attribute named 'd' in yourobj. You are asking for the help of the object that the attribute named 'd' is bound to at that point. The same happens when you access help(yourobj.somefunction), with the only difference that in that particular case, you have a chance to specify a documentation for 'somefunction' and you are unlikely to change "somefunction"'s binding at runtime. So if you need to do something like: [warning: syntax is not valid] class A(object): age = 0 "stores the age of the person" #invalid syntax warning def blablah(self): pass a = A() help(a.age) a.age=7 help(a.age) and always get "stores the age of the person", I don't think python has any syntactical way of doing that. You could simulate it using properties, though (do a 'help(property)' to see an example), but I'm not sure if that will be a good solution. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
Quoting James Stroud <[EMAIL PROTECTED]>: > First, here is why the ability to throw an error is a feature: > > class Apple(object): >def __init__(self, appleness): > self.appleness = appleness >def __cmp__(self, other): > assert isinstance(other, Apple), 'must compare apples to apples' > return cmp(self.appleness, other.appleness) > > class Orange(object): pass > > Apple(42) == Orange() I beg to disagree. The right answer for the question "Am I equal to this chair right here?" is not "I don't know", nor "I can't compare". The answer is "No, I'm not a chair, thus I'm not equal to this chair right here". If someone comes to my house, looking for me, he will not run away because he sees a chair before he sees me. Your assert doesn't belong inside the methot, it should be up to the caller to decide if the human-chair comparisons make sense or not. I certainly don't want to be type-checking when looking for an object within a mixed-type collection. > This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? I assume you meant sqrt(32i). Well, sqrt is a function, and if its result value is defined as 4+4i, then the answer is 'yes', otherwise, the answer should be no. sqrt(4) is *not* -2, and should not be equal to -2. The standard definition of the square root _function_ for real numbers is to take the non-negative real root. I haven't heard of a standard square root _function_ for complex numbers (there is of course, a definition of square root, but it is not a function). So, if by your definition of sqrt, sqrt(32i) returns a number, there is no ambiguity. -2 is not sqrt(4). If you need the answer to be 'True', you may be asking the wrong question. -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
Quoting Rasmus Fogh <[EMAIL PROTECTED]>: > Rhamphoryncus wrote: > > You grossly overvalue using the "in" operator on lists. > > Maybe. But there is more to it than just 'in'. If you do: > >>> c = numpy.zeros((2,)) > >>> ll = [1, c, 3.] > then the following all throw errors: > 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) > c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) > > Note how the presence of c in the list makes it behave wrong for 3 as > well. I think I lost the first messages on this thread, but... Wouldn't be easier to just fix numpy? I see no need to have the == return anything but a boolean, at least on Numpy's case. The syntax 'a == b' is an equality test, not a detailed summary of why they may be different, and (a==b).all() makes no little sense to read unless you know beforehad that a and b are numpy arrays. When I'm comparing normal objects, I do not expect (nor should I) the == operator to return an attribute-by-attribute summary of what was equal and what wasn't. Why is numpy's == overloaded in such a counter intuitive way? I realize that an elementwise comparison makes a lot of sense, but it could have been done instead with a.compare_with(b) (or even better, a.compare_with(b, epsilon=e)). No unexpected breakage, and you have the chance of specifying when you consider two elements to be equal - very useful. Even the transition itself could be done without breaking much code... Make the == op return an object that wraps the array of bools (instead of the array itself), give it the any() and all() methods, and make __nonzero__/__bool__ equivalent to all(). -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
On Wednesday 10 December 2008 10:50:57 am M.-A. Lemburg wrote: > On 2008-12-10 16:40, Luis Zarrabeitia wrote: > > Quoting Rasmus Fogh <[EMAIL PROTECTED]>: > >> Rhamphoryncus wrote: > > Rich comparisons were added to Python at the request of the > Numeric (now numpy) developers and they have been part of Python > a Numeric for many many years. > > I don't think it's likely they'll change things back to the days > of Python 1.5.2 ;-) Please define "rich comparisons" for me. It seems that I do not understand the term - I was thinking it meant the ability to override the comparison operators, and specially, the ability to override them independently. Even in statically typed languages, when you override the equality operator/function you can choose not to return a valid answer (raise an exception). And it would break all the cases mentioned above (element in list, etc). But that isn't the right thing to do. The language doesn't/can't prohibit you from breaking the equality test, but that shouldn't be considered a feature. (a==b).all() makes no sense. > > Even the transition itself could be done without breaking much code... > > Make the == op return an object that wraps the array of bools (instead of > > the array itself), give it the any() and all() methods, and make > > __nonzero__/__bool__ equivalent to all(). > > That would cause a lot of confusion on its own, since such an > object wouldn't behave in the same way as say a regular Python > list (bool([0]) == True). I'm certain that something could be worked out. A quick paragraph that took me just a few minutes to type shouldn't be construed as a PEP that will solve all the problems :D. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
On Wednesday 10 December 2008 02:44:45 pm you wrote: > > Even in statically typed languages, when you override the equality > > operator/function you can choose not to return a valid answer (raise an > > exception). And it would break all the cases mentioned above (element in > > list, etc). But that isn't the right thing to do. The language > > doesn't/can't prohibit you from breaking the equality test, but that > > shouldn't be considered a feature. (a==b).all() makes no sense. > > Perhaps not in your application, but it does make sense in other > numeric applications, e.g. ones that work on vectors or matrixes. > > I'd suggest you simply wrap the comparison in a function and then > have that apply the necessary conversion to a boolean. I do numeric work... I'm finishing my MSc in applied math and I'm programing mostly with python. And I'd rather have a.compare_with(b), or a.elementwise_compare(b), or whatever name, rather than (a==b).all(). In fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() (to account for rounding errors), and with python2.5, all(a.compare_with(b)). Yes, I could create an element_compare(a,b) function. But I still can't use a==b and have a meaningful result. Ok, I can (and do) ignore that, it's just one library, I'll keep track of the types before asking for equality (already an ugly thing to do in python), but the a==b behaviour breaks the lists (a in ll, ll.indexof(a)) even for elements not in numpy. ¿Should I also ignore lists? The concept of equality between two arrays is very well defined, as it is also very well defined the element-by-element comparison. There is a need to test for both - then the way to test for equality should be the equality test. > > I'm certain that something could be worked out. A quick paragraph that > > took me just a few minutes to type shouldn't be construed as a PEP that > > will solve all the problems :D. > > As always: the Devil is in the details :-) Of course... -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
On Sunday 07 December 2008 09:21:18 pm Robert Kern wrote: > The deficiency is in the feature of rich comparisons, not numpy's > implementation of it. __eq__() is allowed to return non-booleans; however, > there are some parts of Python's implementation like list.__contains__() > that still expect the return value of __eq__() to be meaningfully cast to a > boolean. list.__contains__, tuple.__contains__, the 'if' keyword... How do can you suggest to fix the list.__contains__ implementation? Should I wrap all my "if"s with this?: if isinstance(a, numpy.array) or isisntance(b,numpy.array): res = compare_numpy(a,b) elif isinstance(a,some_otherclass) or isinstance(b,someotherclass): res = compare_someotherclass(a,b) ... else: res = (a == b) if res: # do whatever -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python 3.0 string formatting - really necessary?
Quoting r : > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) You forgot 6.) it is the best, cleanest, most consistent and extensible way to do it. > This was the reason for using indention over the bracket plague in > python. REDUNDANCY!!! Why not dump self and make the language cleaner. > I love python's classes, but HATE self.redundant! This really needs to > be fixed, and you have not heard the last from me about it!!! Do you also hate cls.redundant on a classmethod? Would you rather type 'self' even when it is referring to a class? Would you like to resort to a hack, like C#3.0's 'this' explicit argument, when monkey-patching? I used to hate 'self'. Then I met classmethods, metaclasses and decorators, and the 'new'/'types' modules. It's just one of those examples where Guido's time machine works flawlessly. > 3000 would have been the perfect time to dump self and really clean up > the language, and it's not too late, dawn is not upon us yet. No need to wait for python 3000. You can have a 'selfless metaclass' right now: http://www.voidspace.org.uk/python/articles/metaclasses.shtml (BTW, I really hope you are complaining about the explicit self on the argument list, and not about the 'self.' prefix - if that were the case, what magic would you propose for the compiler to guess when you are referring to locals, globals, class or instance variables?) -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Reading from stdin
I have a problem with this piece of code: import sys for line in sys.stdin: print "You said!", line Namely, it seems that the stdin buffers the input, so there is no reply until a huge amount of text has bin written. The iterator returned by xreadlines has the same behavior. The stdin.readline() function doesn't share that behaviour (it returns as soon as I hit 'enter'). ??Is there any way to tell stdin's iterator not to buffer the input? Is it part of the standard file protocol? -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading from stdin
On Tuesday 07 October 2008 05:33:18 pm George Sakkis wrote: > Not an answer to your actual question, but you can keep the 'for' loop > instead of rewriting it with 'while' using the iter(function, > sentinel) idiom: > > for line in iter(sys.stdin.readline, ""): > print "You said!", line You're right, it's not an answer to my actual question, but I had completely forgotten about the 'sentinel' idiom. Many thanks... I was trying to do it with 'itertools', obviously with no luck. The question still stands (how to turn off the buffering), but this is a nice workaround until it gets answered. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading from stdin
On Tuesday 07 October 2008 05:12:28 pm Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Luis
>
> Zarrabeitia wrote:
> > I have a problem with this piece of code:
> >
> >
> > import sys
> > for line in sys.stdin:
> > print "You said!", line
> >
> >
> > Namely, it seems that the stdin buffers the input, so there is no reply
> > until a huge amount of text has bin written. The iterator returned by
> > xreadlines has the same behavior.
> >
> > The stdin.readline() function doesn't share that behaviour (it returns as
> > soon as I hit 'enter').
>
> Perhaps line-buffering simply doesn't apply when you use a file object as
> an iterator.
You cut out the question you replied to, but left the rest. I got a bit
confused until I remembered that *I* wrote the email :D.
Anyway, I changed the program to:
===
buff = file("test")
for line in buff:
print "you said", line
===
where 'test' is a named pipe (mkfifo test) to see if the line-buffering also
happened with a file object, and it does. As with stdin, nothing gets printed
until the end of the file or it receives a huge amount of lines, but
using '.readline()' works immediately. So it seems that the buffering
behavior happens by default on stdin and file. It makes sense, as type(stdin)
is 'file'. I can't test it now, but I think the sockets also do input
buffering. I guess one doesn't notice it on the general case because disk
reading happens too fast to see the delay.
That raises a related question: is there any use-case where is better to lock
the input until a lot of data is received, even when the requested data is
already available? Output buffering is understandable and desired (how do I
turn it off, by the way?), and even that one wont lock unless requested to
lock (flush), but I can't find examples where input buffering helps.
(full example with pipes)
$ mkfifo test
$ cat > test
[write data here]
on another console, just execute the script.
Oh, I forgot:
Linux 2.6.24, python 2.5.2, Debian's standard build. I don't have windows at
hand to try it.
--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading from stdin
On Tuesday 07 October 2008 11:27:19 pm George Sakkis wrote: > """ > In order to make a for loop the most efficient way of looping over the > lines of a file (a very common operation), the next() method uses a > hidden read-ahead buffer. As a consequence of using a read-ahead > buffer, combining next() with other file methods (like readline()) > does not work right. > """ > > I guess the phrasing "hidden read-ahead buffer" implies that buffering > cannot be turned off (or at least it is not intended to even if it's > somehow possible). Hmm. I wonder how those optimizations look like. Apparently, readline() cannot read from that read-ahead buffer, and that by itself sounds bad. Currently, if you loop a few times with next, you cannot use readline afterwards until you seek() to an absolute position. Actually, I think I may be replying to myself here. I imagine that 'next' will read a block instead of a character, and look for lines in there, and as the underlying OS likely blocks until the whole block is read, 'next' cannot avoid it. That doesn't explain, though, why readline() can't use next's buffer, why next doesn't have a sensible timeout for interactive sessions (unless the OS doesn't support it), and why the readahead cannot be turned off. I think I'll have to stick for now with the iter(function,sentinel) solution. And I may try to find next()'s implementation... I guess I'll be downloading python's source when my bandwidth allows it (or find it on a browseable repository) On a related note, help(file.read) shows: = read(...) read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. = But it doesn't say how to put the file object in non-blocking mode. (I was trying to put the file object in non-blocking mode to test next()'s behavior). ??Ideas? -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Parsing a file with iterators
I need to parse a file, text file. The format is something like that: TYPE1 metadata data line 1 data line 2 ... data line N TYPE2 metadata data line 1 ... TYPE3 metadata ... And so on. The type and metadata determine how to parse the following data lines. When the parser fails to parse one of the lines, the next parser is chosen (or if there is no 'TYPE metadata' line there, an exception is thrown). This doesn't work: === for line in input: parser = parser_from_string(line) parser(input) === because when the parser iterates over the input, it can't know that it finished processing the section until it reads the next "TYPE" line (actually, until it reads the first line that it cannot parse, which if everything went well, should be the 'TYPE'), but once it reads it, it is no longer available to the outer loop. I wouldn't like to leak the internals of the parsers to the outside. What could I do? (to the curious: the format is a dialect of the E00 used in GIS) -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: using "private" parameters as static storage?
Quoting Joe Strout <[EMAIL PROTECTED]>: > On Nov 13, 2008, at 10:19 AM, Chris Mellon wrote: > > > Static storage is a way of preserving state. Objects are a way of > > encapsulating state and behavior. Use an object. > > Argh. I've been back in the Python community for about a month, and > I've been continually amazed at how every single "how do I do X" or > "what do you think of this method of doing X" question is answered by > people on high horses claiming "you shouldn't do X". > > I know very well about state and objects. I'll be happy to whip out > my software engineering credentials and measure them against yours if > that's how you like to play. I'm sure your credentials are bigger than mine. But he is right. A lot of languages have ditched the "concept" of a static variable on a method (how do you parse that sentence, btw?) in favour of using encapsulation. Of the top of my head, there is Java, C# and Python, and I think even PHP and Perl. They call them "private variables", including the name-mangled-publicly-accessible-__python's variables. I only know one family of languages that support it: C/C++ (LISP, maybe? I don't remember - my list is very sketchy), but here comes into play the fact that your credentials are bigger. But that may be the reason why you refuse to follow yet another model. Python doesn't have the concept of 'static variables', as in "a variable that remembers its value between function calls". Instance attributes (or class atributes, or metaclass attributes - your choice, depending on the problem) exist for that. So, if you want to simulate your C++ static variables in python, you ha ve a few choices (more than in other languages, btw): * Global variable. Ouch. We really don't want you going there :D * Instance variable. Maybe a __private instance variable, to avoid polluting your descendant's namespaces. * Class/Metaclass variables (if you need them - that's rare). * Closures * Default arguments (too fragile for my taste) * Instance variables _of the function object_. For the last three: (untested code follows) * With closures: === def myfunc(): pseudo_static_list = [] def real_function(args): pseudo_static_list.append(args) print pseudo_static_list return real_function myfunc = myfunc() === [or, until python removes the apply function] === @apply def myfunc(): # same definition as before return real_function === Caveat: you cannot assign, as in python 2.5 at least, to the closure variable - doing so would create a local variable instead. * With default argument: === def myfunc(normal_args, _hidden_arg=[]): _hidden_arg.append(normal_args) print _hidden arg === (You can't shouldn't to _hidden_arg either, and you risk someone invoking the function with that argument) * With function's instance members: === def myfunc(args): myfunc.counter=1 # well, you should use some logic to see if it's not # initialized myfunc.counter+=1 print myfunc.counter === Instance attributes beats them all, though. > I understand very well when data should > be stored as instance data, and when it should be instead tucked away > as static data within a method. OT: Please enlighthen me. I didn't grew with C, and even when I saw C++, instance variables made a lot more sense to me that 'static' variables. > If you don't understand that, or are > happy without having the choice, and have no answer to the question I > was asking, then that's fine. I believe he had an answer... You didn't like it, though. I hope mine was more palatable to you. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: using "private" parameters as static storage?
Quoting Joe Strout <[EMAIL PROTECTED]>: > Hi Luis, > > > A lot of languages have ditched the "concept" of a static variable > > on a method (how do > > you parse that sentence, btw?) in favour of using encapsulation. > > A static variable IS encapsulation. Encapsulation happens at many > levels: module, class, instance, and (in languages that support it) > method. A static local variable is simply the finest level of > encapsulation. (Well, actually you could go one finer in some > languages and have block-level static scope.) But, at least in C++, its really confusing. The 'static' word is reserved on C++ for more than one meaning, but I'll agree that it is a C++ problem and not a problem with the concept. I wish I remembered how and if LISP did it, though. Being LISP, I'd guess their implementation is also based on closures. > > * With closures: > > > > === > > def myfunc(): > >pseudo_static_list = [] > >def real_function(args): > > pseudo_static_list.append(args) > > print pseudo_static_list > >return real_function > > myfunc = myfunc() > > That's interesting -- I'll need to study it further before I really > understand it, so thanks very much. (That's why I ask these > questions; I'm hoping there is some Python feature I haven't yet fully > grokked which applies to the problem at hand.) Well, I love closures :D. And decorators. > No, just adding an instance attribute to the class the method is > already on does not give you the same semantics at all, unless the > class happens to be a singleton. Otherwise, each instance would get > its own cache (or count or whatever -- there are several different use > cases I've seen for this), rather than a shared one. Sometimes that's > acceptable, but often it's not. Not necesarily. One of the things I dislike about 'static' is precisely that it would define the variable's lifetime as 'forever, everywhere'. But as you say, that may not be the only answer. You could need 'as long as _this function_ lives' (python gives you closures for that), 'as long as this object lives' (instance attributes), 'as long as this object's class lives' (class attribute), 'forever' (a global, or a class attribute of a fixed class, that would be like a global but with a namespace). Btw, you can yank a function out of an object and put it on another, if you need your counters to survive that, use closures, if you need your counters to die in that case, you'll have to stick with class or instance attributes. > As noted before, the obvious solution in this case is to use a module- > or class-level variable, prefixed with an underscore. That's not > horrible, but I wanted to explore possible alternatives. Fair enough. > >> I understand very well when data should be stored as instance data, > >> and when it > >> should be instead tucked away as static data within a method. > > > > OT: Please enlighthen me. I didn't grew with C, and even when I saw C > > ++, > > instance variables made a lot more sense to me that 'static' > > variables. > > Maybe a couple examples will help: Thank you. > > I hope mine was more palatable to you. > > Yours was tasty indeed, thanks very much! /me smiles. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Challenge: Please break this! [Python Security]
On Monday 23 February 2009 03:50:57 pm tav wrote: > Hey all, > > As an attempt to convince Python-Dev of the merits of a > functions-based approach to security in Python, I've come up with a > simple challenge. > While I'm almost excited that you are tackling the problem of python's security, I find that your approach seems to break too many things: --- >>> from safelite import FileReader >>> import numeric >>> print numeric None >>> import i_hope_this_doesnt_exists >>> print i_hope_this_doesnt_exists None --- Versus: --- >>> import django >>> print django >>> import i_hope_this_doesnt_exists Traceback (most recent call last): File "", line 1, in ImportError: No module named i_hope_this_doesnt_exists --- ipython also gets broken after the import (nothing works after the import). Still, it seems interesting... -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting screen dims platform specific? Say it ain't so!
On Tuesday 24 February 2009 05:57:52 pm Lionel wrote: > from win32api import GetSystemMetrics I'd guess that win32api is patform specific, as in "api for win32". -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting screen dims platform specific? Say it ain't so!
On Tuesday 24 February 2009 07:12:36 pm Lionel wrote: > In a nutshell, what I need is a way to acquire the screen dimensions > (in pixels) and its dpi setting. This is a guess, and a guess only. What do you want to know it for? If it is for painting something on the screen, maybe (just maybe - I'm guessing here big time), whatever API you are using for painting can be used for getting the dimensions of the drawing device. I don't even know if GTK or Qt have that feature, but you should look into it. If the same api you will use for painting provides that functionality, then it would be kind of irrelevant if it is on the stdlib or not. Of course, this only applies if you want to paint and your api provides that info. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: handling multiple software repositories
On Thursday 26 February 2009 11:10:15 am Tim Golden wrote: > Have a look at DrProject[1], a Trac-alike which handles > multiple projects. (Not used it myself). > > [1] https://www.drproject.org/ I've used DrProject a bit (my gf is one of the developers). If you like trac, chances are that you will love DrProject. It's quite good (and easy to install, unlike gforge), but the developers are moving on to a version 2.0 that you can find around here: http://basieproject.org/ (yeah, the website is ugly). If you like trac, take a look at DrProject and keep an eye on Basie. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
