[issue27803] ctypes automatic byref failing on custom classes attributes

2021-03-05 Thread Terry J. Reedy


Change by Terry J. Reedy :


--
nosy:  -terry.reedy

___
Python tracker 

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



[issue27803] ctypes automatic byref failing on custom classes attributes

2021-03-05 Thread Eryk Sun


Change by Eryk Sun :


--
versions: +Python 3.10, Python 3.8, Python 3.9 -Python 2.7, Python 3.5

___
Python tracker 

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



[issue30692] Automatic upcast does not occur for custom classes

2017-06-17 Thread Ned Deily

Changes by Ned Deily :


--
nosy: +amaury.forgeotdarc, belopolsky, meador.inge

___
Python tracker 

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



[issue30692] Automatic upcast does not occur for custom classes

2017-06-17 Thread Ranger Harke

New submission from Ranger Harke:

I have noticed that the automatic upcast mechanism which works for
standard ctypes types does not appear to work for custom types with
_as_parameter_ defined.

Consider the following example (written for Mac OS X but just change
the LoadLibrary call to test on a different OS):

# -- begin --
from ctypes import *

libc = cdll.LoadLibrary('/usr/lib/libc.dylib')

class Base(Structure): pass
class Derived(Base): pass
class Wrapper(object): pass

printf = libc.printf
printf.argtypes = [ c_char_p, POINTER(Base) ]
printf.restype = c_int

derived = Derived()
derived_ptr = pointer(derived)
derived_ptr_wrapper = Wrapper()
derived_ptr_wrapper._as_parameter_ = pointer(derived)

# Case 1 WORKS: Derived* is automatically upcast to Base* and passed to
#   printf
printf(b'%p\n', derived_ptr)

# Case 2 WORKS: The Wrapper can be explicitly upcast to a Base* and
#   passed to printf
printf(b'%p\n', cast(derived_ptr_wrapper, POINTER(Base)))

# Case 3 FAILS: Automatic upcast does NOT happen with the value in the
#   Wrapper: 'expected LP_Base instance instead of
#   LP_Derived'
printf(b'%p\n', derived_ptr_wrapper)
# -- end --

Here we have two types, Base which is a ctypes Structure, and Derived
which derives from Base. A pointer to Derived can be passed to a
function that expects a pointer to Base, and it will automatically be
upcast.

However, once the Wrapper type is introduced, which simply holds a
pointer to Derived in its _as_parameter_ attribute, the automatic
upcast no longer occurs. A manual upcast works, though.

I believe this may be related to #27803, but that is talking about
byref() whereas this is related to cast(). Perhaps the internal
mechanism is the same; certainly it sounds like a similar problem.

I've tested this in Python 2.7 and 3.6, and the result is the same.

Not sure if this is a bug or an enhancement request- filing it as
"behavior" for now since to me, this is something that I expected to
implicitly work.

Thanks!  - Ranger Harke.

--
components: ctypes
messages: 296245
nosy: rharke
priority: normal
severity: normal
status: open
title: Automatic upcast does not occur for custom classes
type: behavior
versions: Python 2.7, Python 3.6

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



[issue30095] HTMLCalendar allow custom classes

2017-06-06 Thread Walter Dörwald

Walter Dörwald added the comment:

Closing the issue. The patch has been merged.

--
resolution:  -> fixed
stage: patch review -> resolved
status: open -> closed

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-06-06 Thread Walter Dörwald

Walter Dörwald added the comment:


New changeset 8b7a4cc40e9b2f34da94efb75b158da762624015 by Walter Dörwald (Oz N 
Tiram) in branch 'master':
bpo-30095: Make CSS classes used by calendar.HTMLCalendar customizable (GH-1439)
https://github.com/python/cpython/commit/8b7a4cc40e9b2f34da94efb75b158da762624015


--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-06-01 Thread Oz Tiram

Oz Tiram added the comment:

@Walter, I fixed the issues your raised, and also solved the merge conflict in 
What's New.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-06-01 Thread Walter Dörwald

Walter Dörwald added the comment:

See comments on the pull request. Also it seems that currently the pull request 
can't be merged because of merge conflicts.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-05-31 Thread Walter Dörwald

Walter Dörwald added the comment:

See my comments on the pull request: https://github.com/python/cpython/pull/1439

After you address those, IMHO this is ready to be merged.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-05-05 Thread Walter Dörwald

Walter Dörwald added the comment:

See comments on Github

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-05-03 Thread Mariatta Wijaya

Changes by Mariatta Wijaya :


--
stage:  -> patch review
versions: +Python 3.7 -Python 3.6

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-05-03 Thread Oz Tiram

Oz Tiram added the comment:

@Walter,

I implemented your suggestions plus the obvious tasks of adding tests and 
documentation.

Would be happy to hear your feedback.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-05-03 Thread Oz Tiram

Changes by Oz Tiram :


--
pull_requests: +1537

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-24 Thread Oz Tiram

Oz Tiram added the comment:

Apparently, I forgot to push the second branch. It is now pushed.

I renamed the class attribute names on the v1 branch. I still need to do
the following:

 - Add docs
 - Fix existing tests and add new tests demonstrating the usage of the new 
attributes.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-24 Thread Oz Tiram

Oz Tiram added the comment:

@Walter,

I agree with you about consistent naming. Personally, I would prefer to name 
all the variables "styles". But I preferred not to break past compatibility 
too. So I guess we are stuck for a while with "classes". I will rename the 
variables. As for documenting that, I would also do that.
Thanks for the feedback.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-24 Thread Walter Dörwald

Walter Dörwald added the comment:

The second link is a 404.

For the v1 patch:

The variable names are a bit inconsistent: The first uses "classes" all others 
use "styles". This should be consistent within itself and with the existing 
code, i.e. "classes" should be used.

Also each class attribute should be preceded with a comment, explaining what 
the CSS class is used for.

As these are now made public to be overwritten by subclasses, I wonder wether 
it would make sense to document these class attributes in 
Doc/library/calendar.rst

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-23 Thread Oz Tiram

Oz Tiram added the comment:

@Walter, 

I implemented two possible solutions. Chronologically speaking V2 was 
implemented before V1, but it's a bit über-smart and might surprise it's
users requiring the class attributes to be some kind of iterable.

The first version is my current preferred solution.

I intentionally didn't create a PR for that yet. 

These are the branches:

https://github.com/oz123/cpython/tree/issue30095-v1
https://github.com/oz123/cpython/tree/issue30095-v2

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-19 Thread Walter Dörwald

Walter Dörwald added the comment:

OK, go ahead. I'm looking forward to what you come up with.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-19 Thread Oz Tiram

Oz Tiram added the comment:

... Using class attributes would nice, also considering that the days CSS 
classes are defined as class attributes.

I meant to write :

Using class attributes would be nicer, also considering that the days CSS 
classes are defined as class attributes.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-19 Thread Oz Tiram

Oz Tiram added the comment:

@doerwalter, exactly. I found myself overwriting the relevant methods too many 
times.

I usually did something like this:

class WorkCalendar(HTMLCalendar):

def formatmonthname(self, theyear, themonth, withyear=True,
style=r'class="month-head"'):
 
"""
Return a month name as a table row.
"""
monthname = super().formatmonthname(theyear, themonth, withyear)
regex = r'class\="month"'
return re.sub(regex, style, monthname, 1)


Using class attributes would nice, also considering that the days CSS classes 
are defined as class attributes.

My intention was a few more class attributes (for the month header, and month) 
and also change the existing code such that each day can have multiple CSS 
classes and not just one.

I am willing to work on a PR for that if that sounds good and there is someone 
who would be willing to merge it.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-19 Thread Walter Dörwald

Walter Dörwald added the comment:

IMHO this could all be done by overwriting the relevant methods.

But this might be overkill.

I think a solution might be to move the CSS classes into class attributes of 
HTMLCalendar. Customizing the CSS classes would then be done by subclassing 
HTMLCalendar and overwriting the appropriate class attributes.

Is this what you had in mind?

--
nosy: +doerwalter

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-18 Thread Serhiy Storchaka

Changes by Serhiy Storchaka :


--
nosy: +rhettinger

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-18 Thread Oz Tiram

Oz Tiram added the comment:

Of course I can, but I can't add multiple css classes, and I forced to
have the same class for both the title of the month and the body of the month.

--

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-18 Thread Mariatta Wijaya

Mariatta Wijaya added the comment:

Can't you override the `.month` css class and customize the style that way?

--
nosy: +Mariatta

___
Python tracker 

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



[issue30095] HTMLCalendar allow custom classes

2017-04-18 Thread Oz Tiram

New submission from Oz Tiram:

At the moment methods like HTMLCalendar.formatmonthname and 
HTMLCalendar.formatmonth have hard coded name 'month'.

This class is pretty helpful as a good start, but if you want to customize
the styles it's not helpful.

I think it would be helpful for others too, if this would have be customize 
able.

Would you accept a PR for such thing?

--
components: Library (Lib)
messages: 291841
nosy: Oz.Tiram
priority: normal
severity: normal
status: open
title: HTMLCalendar allow custom classes
type: enhancement
versions: Python 3.6

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



[issue27803] ctypes automatic byref failing on custom classes attributes

2016-08-29 Thread Erwan Le Pape

Erwan Le Pape added the comment:

I can confirm Eryk got what I meant. I didn't know if it was meant to work that 
way or if it was simply something that was overlooked so I thought I'd ask, I 
will look into the ctypes code to provide a patch sometime this week if I can.

Terry, for a working example take the following (on a MS Windows):
>>> from ctypes import *
>>> from ctypes.wintypes import *
>>>
>>> class CustomPHKEY(object):
... def __init__(self, value):
... self._as_parameter_ = HKEY(value)
...
>>>
>>> function = ctypes.windll.advapi32.RegOpenKeyExW
>>> function.argtypes = [HKEY, c_wchar_p, DWORD, DWORD, POINTER(HKEY)]
>>> function.restype = LONG
>>> result = CustomPHKEY(0)
>>> function(0x8002, 'SOFTWARE', 0, 0x20019, result)
Traceback (most recent call last):
  File "", line 1, in 
ctypes.ArgumentError: argument 5: : expected 
LP_c_void_p instance instead of c_void_p

--

___
Python tracker 

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



[issue27803] ctypes automatic byref failing on custom classes attributes

2016-08-26 Thread Eryk Sun

Eryk Sun added the comment:

Terry, the provided example is incomplete and doesn't make sense as it stands. 
For better or worse, windll.dllname attempts to load WinDLL(dllname) and cache 
the resulting library on the windll loader. (The library in turn caches 
function pointers, which means this design is a problem waiting to happen, 
which has happened a few times with various projects conflicting with each 
other over windll.kernel32 function prototypes. I recommend using WinDLL 
instead.)

I gather that Erwan wants ctypes.byref() and the implicit _byref that's called 
by PyCPointerType_from_param to be enhanced to support objects that define 
_as_parameter_. So I'm changing the issue type accordingly.

--
nosy: +eryksun
type: behavior -> enhancement

___
Python tracker 

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



[issue27803] ctypes automatic byref failing on custom classes attributes

2016-08-26 Thread Terry J. Reedy

Terry J. Reedy added the comment:

I ran the the following, which I don't understand, and therefore don't what 
should happen, on Win 10, 3.6.0a3.

from ctypes import *
from ctypes.wintypes import *

class CustomPHKEY(object):
def __init__(self, value):
self._as_parameter_ = HKEY(value)

function = windll.function
function.argtypes = [POINTER(HKEY)]
function.restype = LONG
result = CustomPHKEY(0)
function(result)

Traceback (most recent call last):
  File "F:\Python\mypy\tem.py", line 8, in 
function = windll.function
  File "C:\Programs\Python36\lib\ctypes\__init__.py", line 417, in __getattr__
dll = self._dlltype(name)
  File "C:\Programs\Python36\lib\ctypes\__init__.py", line 347, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found

--
nosy: +terry.reedy

___
Python tracker 

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



[issue27803] ctypes automatic byref failing on custom classes attributes

2016-08-19 Thread Erwan Le Pape

New submission from Erwan Le Pape:

When using a custom class to store a ctype value, passing that class as a 
function argument explicitly declared to be a pointer type fails to pass the 
_as_parameter_ class attribute as a pointer and instead raises a TypeError.

For example:
>>> from ctypes import *
>>> from ctypes.wintypes import *
>>>
>>> class CustomPHKEY(object):
... def __init__(self, value):
... self._as_parameter_ = HKEY(value)
...
>>>
>>> function = windll.function
>>> function.argtypes = [POINTER(HKEY)]
>>> function.restype = LONG
>>> result = CustomPHKEY(0)
>>> function(result)
Traceback (most recent call last):
  File "", line 1, in 
ctypes.ArgumentError: argument 1: : expected 
LP_c_void_p instance instead of c_void_p

Shouldn't ctypes apply the required byref() conversion automatically? Or is 
this behavior normal and automatic byref() only concerns native ctypes types?

I only flagged Python 3.5 and Python 2.7 since they are the only ones I 
explicitly tested this on but I suspect other versions are affected.

--
components: ctypes
messages: 273149
nosy: amaury.forgeotdarc, belopolsky, lepaperwan, meador.inge
priority: normal
severity: normal
status: open
title: ctypes automatic byref failing on custom classes attributes
type: behavior
versions: Python 2.7, Python 3.5

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



Re: Custom Classes?

2008-05-15 Thread Gabriel Genellina
En Tue, 13 May 2008 15:10:21 -0300, Victor Subervi  
[EMAIL PROTECTED] escribió:



I remember why I had the number with the getpic. It is because I display
several of these images on a single page, and apparently I cannot call  
the

same script and get more than one image from an HTML page.


That's not true. If you still have the example I posted a few weeks ago,  
you can use this script to show a full listing of all uploaded pictures.  
It's a small variation of album.py.
I think you were saving the pictures on disk - DON'T do that. It's  
unnecesary, wastes time and disk space, and if not done properly one  
request interferes with the other.


--
Gabriel Genellina#!/usr/bin/python

Full listing (all pictures)

import cgi
import sqlite3

conn = sqlite3.connect(demo.db)
cursor = conn.cursor()
sql = select id, title, description from album order by id
cursor.execute(sql)
lines = []
for row in cursor.fetchall():
id, title, description = row
lines.append(h2%s/h2
 p%sbr
   img src='getpic.py?id=%s'
 /p % (cgi.escape(title), 
  cgi.escape(description), 
  id))
conn.close()

print Content-Type: text/html
print Pragma: no-cache 
print Cache-Control: no-cache
print
print htmlheadtitlePicture album (full)/title/head
print body
print h1Picture album/h1
if lines:
print \n.join(lines)
else:
print No pictures yet.
print pYou can a href='upload.py'upload a new picture/a./p
print /body/html
--
http://mail.python.org/mailman/listinfo/python-list

Re: Custom Classes?

2008-05-15 Thread Victor Subervi
Well, you are right. It looks like one of those instances where I fixed
something and did not check to see if it influenced the problem now at hand.
Thanks again.
Victor


On 5/15/08, Gabriel Genellina [EMAIL PROTECTED] wrote:

 En Tue, 13 May 2008 15:10:21 -0300, Victor Subervi 
 [EMAIL PROTECTED] escribió:

 I remember why I had the number with the getpic. It is because I display
 several of these images on a single page, and apparently I cannot call the
 same script and get more than one image from an HTML page.


 That's not true. If you still have the example I posted a few weeks ago,
 you can use this script to show a full listing of all uploaded pictures.
 It's a small variation of album.py.
 I think you were saving the pictures on disk - DON'T do that. It's
 unnecesary, wastes time and disk space, and if not done properly one request
 interferes with the other.

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


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

Re: Custom Classes?

2008-05-13 Thread Victor Subervi
On 5/9/08, Gabriel Genellina [EMAIL PROTECTED] wrote:

 En Thu, 08 May 2008 12:33:55 -0300, Victor Subervi 
 [EMAIL PROTECTED] escribió:

 Okay, trying this again with everything working and no ValueError or any
  other errors, here we go:
 

 getpic = getpic + str(w) + .py
 

 Why do you *generate* the getpicNN.py? It contains always the same code,
 why don't you just use a single getpic.py?

 and then surf to:
  http://whatever.url/getpic20.py?id=6x=1


Because I initially could not get it to work that way...and then I forgot
about it. But you are right. That is what I need to do. So I will work on
that.

Uhm, I don't think there is something specific for this list. There is an
 article from E.S.Raymond How to ask questions the smart way? that you can
 find with Google


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

Re: Custom Classes?

2008-05-13 Thread Victor Subervi
I remember why I had the number with the getpic. It is because I display
several of these images on a single page, and apparently I cannot call the
same script and get more than one image from an HTML page.
Victor

On Fri, May 9, 2008 at 10:26 AM, Gabriel Genellina [EMAIL PROTECTED]
wrote:

 En Thu, 08 May 2008 12:33:55 -0300, Victor Subervi 
 [EMAIL PROTECTED] escribió:

 Okay, trying this again with everything working and no ValueError or any
  other errors, here we go:
 

  getpic = getpic + str(w) + .py
 

 Why do you *generate* the getpicNN.py? It contains always the same code,
 why don't you just use a single getpic.py?

 and then surf to:
  http://whatever.url/getpic20.py?id=6x=1
 

 Why don't you post the error you get instead...? Including the complete
 exception report.

 Also, please re-send the link on how to post good questions to the list. I
  cannot find it.
 

 Uhm, I don't think there is something specific for this list. There is an
 article from E.S.Raymond How to ask questions the smart way? that you can
 find with Google

 --
 Gabriel Genellina

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

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

Dynamic generation of images (was Re: Custom Classes?)

2008-05-09 Thread J. Cliff Dyer
On Thu, 2008-05-08 at 10:33 -0500, Victor Subervi wrote:
 Okay, trying this again with everything working and no ValueError or
 any other errors, here we go:
 
 Load this code. Unless you use a similar login() script, you will want
 to edit your own values into the user, passwd, db and host:
 
 #!/usr/bin/python
 
 import MySQLdb
 
 import sys,os
 sys.path.append(os.getcwd())
 from login import login
 user, passwd, db, host = login()
 
 pic = pic1
 w = 20
 x = 0
 d = 6
 y = 1
 
 getpic = getpic + str(w) + .py
 try:
   os.remove(getpic)
 except:
   pass
 code = 
 #!/usr/local/bin/python
 import cgitb; cgitb.enable()
 import MySQLdb
 import cgi
 import sys,os
 sys.path.append(os.getcwd())
 from login import login
 user, passwd, db, host = login()
 form = cgi.FieldStorage()
 picid = int(form[id].value)
 x = int(form[x].value)
 pics =
 {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
 pic = pics[x]
 db = MySQLdb.connect(host, user, passwd, db)
 cursor= db.cursor()
 sql = select %s from products where id='%s'; % (pic, str(picid))
 
 cursor.execute(sql)
 content = cursor.fetchall()[0][0].tostring()
 cursor.close()
 print 'Content-Type: image/jpeg'
 print
 print content
 
 script = open(getpic, w)
 script.write(code)
 script.close()
 
 
 
 and then surf to:
 http://whatever.url/getpic20.py?id=6x=1
 
 
 Also, please re-send the link on how to post good questions to the
 list. I cannot find it.
 TIA,
 Victor

Why are you dynamically creating getpic20.py?

Obviously, in the real script, you probably have several of them:
getpic1.py, getpic2.py, etc., but is there any reason you couldn't just
have one getpic.py, and pass the number in as a parameter in your GET
request, like this:

http://localhost/getpic.py?id=6x=1w=20

Then you can just have a static getpic.py.  I've stripped out useless
bits:

* You don't use sys or os, so why import them?
* MySQL makes it difficult for me to replicate your behavior, because I 
  don't have your DB setup.  The DB call has been replaced with a
  dictionary of keys into JPG data, pulled from the filesystem.  Change 
  filenames to jpegs on your own hard drive
* login is useless without MySQL.

So your new getpic.py (statically created) looks like this:

~~~ getpic.py ~~~
#!/usr/local/bin/python

import cgitb; cgitb.enable()
import cgi

pics = { 
1: open('pic.jpg').read(),
2: open('pic2.jpg').read()
}
# you could just pass the filename, and then you wouldn't have to load
the
# image data in advance, but this more closely mimics the concept of
your DB 
# setup.

form = cgi.FieldStorage()
x = int(form[x].value)
pic = pics[x]

print 'Content-Type: image/jpeg'
print
print pic
~~~

Then if you want to include your pictures in a web page, you do

~~~ show_pics.html ~~~
html
  headtitlePictures/title/head
  body
h1pictures/h1
img src='http://example.com/getpic.py?x=1'/
img src='http://example.com/getpic.py?x=2'/
  /body
/html
~~~

This should work just as well when you refactor the script to pull from
the database.

Hope this helps.  Also, the article on asking good questions is
available here:  http://catb.org/~esr/faqs/smart-questions.html



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


Re: Custom Classes?

2008-05-08 Thread Victor Subervi
Okay, trying this again with everything working and no ValueError or any
other errors, here we go:

Load this code. Unless you use a similar login() script, you will want to
edit your own values into the user, passwd, db and host:

#!/usr/bin/python

import MySQLdb

import sys,os
sys.path.append(os.getcwd())
from login import login
user, passwd, db, host = login()

pic = pic1
w = 20
x = 0
d = 6
y = 1

getpic = getpic + str(w) + .py
try:
  os.remove(getpic)
except:
  pass
code = 
#!/usr/local/bin/python
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
user, passwd, db, host = login()
form = cgi.FieldStorage()
picid = int(form[id].value)
x = int(form[x].value)
pics =
{1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
pic = pics[x]
db = MySQLdb.connect(host, user, passwd, db)
cursor= db.cursor()
sql = select %s from products where id='%s'; % (pic, str(picid))

cursor.execute(sql)
content = cursor.fetchall()[0][0].tostring()
cursor.close()
print 'Content-Type: image/jpeg'
print
print content

script = open(getpic, w)
script.write(code)
script.close()



and then surf to:
http://whatever.url/getpic20.py?id=6x=1


Also, please re-send the link on how to post good questions to the list. I
cannot find it.
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Re: Custom Classes?

2008-05-08 Thread Gabriel Genellina
En Thu, 08 May 2008 12:33:55 -0300, Victor Subervi  
[EMAIL PROTECTED] escribió:



Okay, trying this again with everything working and no ValueError or any
other errors, here we go:



getpic = getpic + str(w) + .py


Why do you *generate* the getpicNN.py? It contains always the same code,  
why don't you just use a single getpic.py?



and then surf to:
http://whatever.url/getpic20.py?id=6x=1


Why don't you post the error you get instead...? Including the complete  
exception report.


Also, please re-send the link on how to post good questions to the list.  
I cannot find it.


Uhm, I don't think there is something specific for this list. There is an  
article from E.S.Raymond How to ask questions the smart way? that you  
can find with Google


--
Gabriel Genellina

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


Re: Custom Classes?

2008-05-02 Thread J. Clifford Dyer
On Thu, 2008-05-01 at 17:31 -0500, Victor Subervi wrote:
 On Wed, Apr 30, 2008 at 12:35 PM, J. Cliff Dyer [EMAIL PROTECTED] wrote:
 Post working code, and I'll answer your actual question.
 
 Good grief!  The code is *not* double spaced! Take a look. Click to
 the end of the first line and hit the right arrow key, and see for
 yourself.  As for not initializing w, well, I did in my code and just
 forgot to cut and paste that. Same with the except. Sorry on those.
 And yes, I pull out try clauses when I need to look at stacks. Here:

Taking a closer look--it's still double spaced, but I'm sure that's just
something funky in how it's getting rendered along the way.  

That said, your code still doesn't work.  After removing your try
statements, and the corresponding except-pass blocks, I get the
following problems:

Traceback (most recent call last):
  File test.py, line 5, in module
os.remove(getpic)
NameError: name 'os' is not defined

and when I fix that:

Traceback (most recent call last):
  File test.py, line 34, in module
print 'tdinput type=hidden name=%s' % str(x), ' value=%s'
% pic

Please test your code snippet before you post it.  Testing the program
you extracted it from is not sufficient.

On line 34 (or thereabouts--I had to add a line for import os, and
stripped out all blank lines, since my email client is still rendering
it double spaced), I think you wanted x instead of str(x).  At least,
that's what your generated script wants.  str(x) takes the value of the
variable x (not yet defined), and converts it to a str.  It does not
give you a str with a value of x.  

As for the generated script, why are you creating that on the fly every
time?  Why not just create it as an independent python file?  When you
want an image displayed in another HTML file, static or generated, just
point your src to that python file with the appropriate arguments.

img src='http://example.com/path/to/getpic.py?x=4'/

Also, remove the line that says print 'Content-Type: text/html'.  You
only need one content type, and it should be image/jpeg, or whatever
type your images are.  If you are going to have a few pngs in there as
well, for example, you'll need some mechanism for determining what type
of image the file actually is, and outputting the appropriate header
from:

Content-Type: image/jpeg
Content-Type: image/png
Content-Type: image/gif

This could be by checking the file extension, probing the file itself,
or by including the mime-type in your pics dictionary like so:

pics = {1: ('pic1', 'image/jpeg'), 2: ('pict_num_two', 'image/png')} 


Then, of course, you'll have to revise how you retrieve the information.

That should be enough to get you moving in the right direction.

Cheers,
Cliff
 
 
 w = 0
 
 
 try:
 
   w += 1
 
   getpic = getpic + str(w) + .py
 
   try:
 
 os.remove(getpic)
 
   except:
 
 pass
 
   code = 
 
 #!/usr/local/bin/python
 
 import cgitb; cgitb.enable()
 
 import MySQLdb
 
 import cgi
 
 import sys,os
 
 sys.path.append(os.getcwd())
 
 from login import login
 
 user, passwd, db, host = login()
 
 form = cgi.FieldStorage()
 
 picid = int(form[id].value)
 
 x = int(form[x].value)
 
 pics =
 {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
 
 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
 
 pic = pics[x]
 
 print 'Content-Type: text/html'
 
 db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
 
 cursor= db.cursor()
 
 sql = select  + pic +  from products where id=' + str(picid) +
 ';
 
 cursor.execute(sql)
 
 content = cursor.fetchall()[0][0].tostring()
 
 cursor.close()
 
 print 'Content-Type: image/jpeg'
 
 print
 
 print content
 
 
 
   script = open(getpic, w)
 
   script.write(code)
 
   print 'tdinput type=hidden name=%s' % str(x), ' value=%s'
 % pic
 
   print 'img src=%s?id=%dx=%dbr /br //td\n' % (getpic, d,
 y)
 
 except:
 
   pass
 
 
 TIA,
 Victor
 
-- 
Oook!
J. Cliff Dyer
Carolina Digital Library and Archives
UNC Chapel Hill

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

Re: Custom Classes?

2008-05-02 Thread Victor Subervi
Thank you for your patience. I apologize for so many errors. Also,
apparently your email client renders those double-spaces whereas mine does
not. Hopefully the below is better:

#!/usr/bin/python

import MySQLdb
import sys,os
sys.path.append(os.getcwd())
from login import login
user, passwd, db, host = login()

pic = pic1
w = 20
x = 0
d = 6
y = 1
getpic = getpic + str(w) + .py
try:
  os.remove(getpic)
except:
  pass
code = 
#!/usr/local/bin/python
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
user, passwd, db, host = login()
form = cgi.FieldStorage()
picid = int(form[id].value)
x = int(form[x].value)
pics =
{1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
pic = pics[x]
db = MySQLdb.connect(host, user, passwd, db)
cursor= db.cursor()
sql = select %s from products where id='%s'; % (pic, str(picid))
cursor.execute(sql)
content = cursor.fetchall()[0][0].tostring()
cursor.close()
print 'Content-Type: image/jpeg'
print
print content

script = open(getpic, w)
script.write(code)
# print 'tdinput type=hidden name=%s value=%s /' % (str(x),  pic)
# print 'img src=%s?id=%dx=%dbr /br //td\n' % (getpic, d, y)
print 'img src=getpic20.py?id=6x=1\n'



Now, on those last 3 lines, I am having trouble with this error being thrown
that I don´t understand:
ValueError: unpack list of wrong size
If I surf to the given url, the image appears! So what gives?? Furthermore,
the code works just fine from where it was lifted.
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Re: Custom Classes?

2008-05-01 Thread Victor Subervi
On Wed, Apr 30, 2008 at 12:35 PM, J. Cliff Dyer [EMAIL PROTECTED] wrote:

 Post working code, and I'll answer your actual question.


Good grief!  The code is *not* double spaced! Take a look. Click to the end
of the first line and hit the right arrow key, and see for yourself.  As for
not initializing w, well, I did in my code and just forgot to cut and paste
that. Same with the except. Sorry on those. And yes, I pull out try clauses
when I need to look at stacks. Here:

w = 0

try:

  w += 1

  getpic = getpic + str(w) + .py

  try:

os.remove(getpic)

  except:

pass

  code = 

#!/usr/local/bin/python

import cgitb; cgitb.enable()

import MySQLdb

import cgi

import sys,os

sys.path.append(os.getcwd())

from login import login

user, passwd, db, host = login()

form = cgi.FieldStorage()

picid = int(form[id].value)

x = int(form[x].value)

pics =
{1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\

9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}

pic = pics[x]

print 'Content-Type: text/html'

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)

cursor= db.cursor()

sql = select  + pic +  from products where id=' + str(picid) + ';

cursor.execute(sql)

content = cursor.fetchall()[0][0].tostring()

cursor.close()

print 'Content-Type: image/jpeg'

print

print content



  script = open(getpic, w)

  script.write(code)

  print 'tdinput type=hidden name=%s' % str(x), ' value=%s' % pic

  print 'img src=%s?id=%dx=%dbr /br //td\n' % (getpic, d, y)

except:

  pass


TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Custom Classes?

2008-04-30 Thread Victor Subervi
 Hi;
I have the following code which produces a file every time I need to display
an image from MySQL. What garbage! Surely, python is capable of better than
this, but the last time I asked for help on it, I got no responses. Is this
only possible with custom classes? Please, give me some guidance here!

try:

  w += 1

  getpic = getpic + str(w) + .py

  try:

os.remove(getpic)

  except:

pass

  code = 

#!/usr/local/bin/python

import cgitb; cgitb.enable()

import MySQLdb

import cgi

import sys,os

sys.path.append(os.getcwd())

from login import login

user, passwd, db, host = login()

form = cgi.FieldStorage()

picid = int(form[id].value)

x = int(form[x].value)

pics =
{1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\

9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}

pic = pics[x]

print 'Content-Type: text/html'

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)

cursor= db.cursor()

sql = select  + pic +  from products where id=' + str(picid) + ';

cursor.execute(sql)

content = cursor.fetchall()[0][0].tostring()

cursor.close()

print 'Content-Type: image/jpeg'

print

print content



  script = open(getpic, w)

  script.write(code)

  print 'tdinput type=hidden name=%s' % str(x), ' value=%s' % pic

  print 'img src=%s?id=%dx=%dbr /br //td\n' % (getpic, d, y)

TIA,

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

Re: Custom Classes?

2008-04-30 Thread J. Cliff Dyer


On Wed, 2008-04-30 at 11:02 -0500, Victor Subervi wrote:
 Hi;
 I have the following code which produces a file every time I need to
 display an image from MySQL. What garbage! Surely, python is capable
 of better than this, but the last time I asked for help on it, I got
 no responses. Is this only possible with custom classes? Please, give
 me some guidance here!
 try:
 
   w += 1
 
   getpic = getpic + str(w) + .py
 
   try:
 
 os.remove(getpic)
 
   except:
 
 pass
 
   code = 
 
 #!/usr/local/bin/python
 
 import cgitb; cgitb.enable()
 
 import MySQLdb
 
 import cgi
 
 import sys,os
 
 sys.path.append(os.getcwd())
 
 from login import login
 
 user, passwd, db, host = login()
 
 form = cgi.FieldStorage()
 
 picid = int(form[id].value)
 
 x = int(form[x].value)
 
 pics =
 {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
 
 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
 
 pic = pics[x]
 
 print 'Content-Type: text/html'
 
 db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
 
 cursor= db.cursor()
 
 sql = select  + pic +  from products where id=' + str(picid) +
 ';
 
 cursor.execute(sql)
 
 content = cursor.fetchall()[0][0].tostring()
 
 cursor.close()
 
 print 'Content-Type: image/jpeg'
 
 print
 
 print content
 
 
 
   script = open(getpic, w)
 
   script.write(code)
 
   print 'tdinput type=hidden name=%s' % str(x), ' value=%s'
 % pic
 
   print 'img src=%s?id=%dx=%dbr /br //td\n' % (getpic, d,
 y)
 
  
 TIA,
 Victor

Victor,

Once again, you've posted code that doesn't work.  Your outer try block
is never terminated, and w is never initialized (so will raise an
exception inside your try block, which you probably won't see, if you
catch all exceptions.  Generally speaking, unless you know what you're
trying to catch, it's better to leave off the try/except block,
*especially* during development.  Stack traces are full of good
information.

Second, you never initialize w, which causes the following problem.  

$  python
Python 2.3.4 (#1, Nov 20 2007, 15:18:15) 
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type help, copyright, credits or license for more information.
 w += 1
Traceback (most recent call last):
  File stdin, line 1, in ?
NameError: name 'w' is not defined
 

Third, double-spacing your code makes it difficult to read.  Take out
blank lines, unless they add contextual hints which improve readability.

Post working code, and I'll answer your actual question.

Cheers,
Cliff


 
-- 
Oook,
J. Cliff Dyer
Carolina Digital Library and Archives
UNC Chapel Hill

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


Re: custom classes in sets

2005-02-14 Thread vegetax
Steven Bethard wrote:

 vegetax wrote:
 How can i make my custom class an element of a set?
 
 class Cfile:
   def __init__(s,path): s.path = path
 
   def __eq__(s,other):
print 'inside equals'
return not os.popen('cmp %s %s' % (s.path,other.path)).read()
 
   def __hashcode__(s): return s.path.__hashcode__()
 
 the idea is that it accepts file paths and construct a set of unique
 files (the command cmp compares files byte by byte.),the files can
 have different paths but the same content
 
 but the method __eq__ is never called
 
 Seems to be called fine for me:
 
 py class Cfile:
 ... def __eq__(self, other):
 ... print 'inside equals'
 ... return False
 ... def __hash__(self):
 ... return 0
 ...
 py {Cfile():1, Cfile():2}
 inside equals
 {__main__.Cfile instance at 0x01166490: 1, __main__.Cfile instance at
 0x01166760: 2}
 
 Note that __eq__ won't be called if the hashes are different:

I just tried and it wont be called =(, so how can i generate a hash code for
the CFile class? note that the comparitions(__eq__) are done based on the
contents of a file using the command 'cmp', i guess thats not posible but 
thanks.

 


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


Re: custom classes in sets

2005-02-14 Thread Nick Coghlan
vegetax wrote:
How can i make my custom class an element of a set?
class Cfile:
  def __init__(s,path): s.path = path
  def __eq__(s,other):
   print 'inside equals'
   return not os.popen('cmp %s %s' % (s.path,other.path)).read()
  def __hashcode__(s): return s.path.__hashcode__()
the idea is that it accepts file paths and construct a set of unique 
files (the command cmp compares files byte by byte.),the files can
have different paths but the same content

but the method __eq__ is never called
Your problem is that your class defines an insane hash. For a sane hash, A == B 
implies hash(A) == hash(B), whereas you have based your hash on the path to the 
files, but the comparison on the contents of the files. If the paths are all 
different, then nothing is likely to hash the same, so the set will never get 
around to trying the direct comparison.

Change the hash method to use the size of the file or something else that has to 
be equal for the comparison to be equal (like the hash of the first line, or of 
the entire file), and you should see much better behaviour.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: custom classes in sets

2005-02-14 Thread Carl Banks
vegetax wrote:
 Steven Bethard wrote:

  vegetax wrote:
  How can i make my custom class an element of a set?
 
  class Cfile:
def __init__(s,path): s.path = path
 
def __eq__(s,other):
 print 'inside equals'
 return not os.popen('cmp %s %s' % (s.path,other.path)).read()
 
def __hashcode__(s): return s.path.__hashcode__()
 
  the idea is that it accepts file paths and construct a set of
unique
  files (the command cmp compares files byte by byte.),the files
can
  have different paths but the same content
 
  but the method __eq__ is never called

[snip]

 I just tried and it wont be called =(, so how can i generate a hash
code for
 the CFile class? note that the comparitions(__eq__) are done based on
the
 contents of a file using the command 'cmp', i guess thats not posible
but
 thanks.


Let me suggest that, if your idea is to get a set of files all with
unique file contents, comparing a file byte-by-byte with each file
already in the set is going to be absurdly inefficient.

Instead, I recommend comparing md5 (or sha) digest.  The idea is, you
read in each file once, calculate an md5 digest, and compare the
digests instead of the file contents.

. import md5
.
. class Cfile:
. def __init__(self,path):
. self.path = path
. self.md5 = md5.new().update(open(path).read()).digest()
. def __eq__(self,other):
. return self.md5 == other.md5
. def __hash__(self):
. return hash(self.md5)

This is kind of hackish (not to mention untested).  You would probably
do better to mmap the file (see the mmap module) rather than read it.

And, in case you're wondering: yes it is theoretically possible for
different files to have the same md5.  However, the chances are
microscopic.  (Incidentally, the SCons build system uses MD5 to decide
if a file has been modified.)


-- 
CARL BANKS

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


Re: custom classes in sets

2005-02-14 Thread John Machin

vegetax wrote:
 How can i make my custom class an element of a set?

 the idea is that it accepts file paths and construct a set of unique
 files (the command cmp compares files byte by byte.),the files can
 have different paths but the same content


Q: How do I transport ten sumo wrestlers on a unicycle?

A: With extreme difficulty. You may well need a different vehicle.

Think about your requirements, then implement the most appropriate data
structure. If, as is likely, you need to know which and how many files
are identical, then a set won't do the job by itself. You may need a
union-find gadget.

Then before you rush and implement something, google around and look in
the Tools and Scripts directories in the Python distribution; I'm quite
sure I've seen something like a duplicate file detector written in
Python somewhere.

HTH,
John

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


Re: custom classes in sets

2005-02-14 Thread Fredrik Lundh
John Machin wrote:

 Then before you rush and implement something, google around and look in
 the Tools and Scripts directories in the Python distribution; I'm quite
 sure I've seen something like a duplicate file detector written in
 Python somewhere.

first google hit:

http://sebsauvage.net/python/doublesdetector.py

/F 



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


custom classes in sets

2005-02-13 Thread vegetax
How can i make my custom class an element of a set?

class Cfile:
  def __init__(s,path): s.path = path

  def __eq__(s,other):
   print 'inside equals'
   return not os.popen('cmp %s %s' % (s.path,other.path)).read()

  def __hashcode__(s): return s.path.__hashcode__()

the idea is that it accepts file paths and construct a set of unique 
files (the command cmp compares files byte by byte.),the files can
have different paths but the same content

but the method __eq__ is never called

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


RE: custom classes in sets

2005-02-13 Thread Delaney, Timothy C (Timothy)
vegetax wrote:

   def __hashcode__(s): return s.path.__hashcode__()

Try __hash__ ...

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


RE: custom classes in sets

2005-02-13 Thread vegetax
Delaney, Timothy C (Timothy) wrote:

 vegetax wrote:
 
   def __hashcode__(s): return s.path.__hashcode__()
 
 Try __hash__ ...
 
 Tim Delaney

sorry about the typo, it is indead __hash__() that i tried

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


Re: custom classes in sets

2005-02-13 Thread Steven Bethard
vegetax wrote:
How can i make my custom class an element of a set?
class Cfile:
  def __init__(s,path): s.path = path
  def __eq__(s,other):
   print 'inside equals'
   return not os.popen('cmp %s %s' % (s.path,other.path)).read()
  def __hashcode__(s): return s.path.__hashcode__()
the idea is that it accepts file paths and construct a set of unique 
files (the command cmp compares files byte by byte.),the files can
have different paths but the same content

but the method __eq__ is never called
Seems to be called fine for me:
py class Cfile:
... def __eq__(self, other):
... print 'inside equals'
... return False
... def __hash__(self):
... return 0
...
py {Cfile():1, Cfile():2}
inside equals
{__main__.Cfile instance at 0x01166490: 1, __main__.Cfile instance at 
0x01166760: 2}

Note that __eq__ won't be called if the hashes are different:
py class Cfile:
... hash = 0
... def __eq__(self, other):
... print 'inside equals'
... return False
... def __hash__(self):
... Cfile.hash += 1
... return Cfile.hash
...
py {Cfile():1, Cfile():2}
{__main__.Cfile instance at 0x01166918: 1, __main__.Cfile instance at 
0x011668A0: 2}

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