473,575 Members | 3,401 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PATCH: sets.py for Jython 2.1

Hola,

I made a backport of sets.py that will run on Jython 2.1. Here is a diff
against the Python 2.3 version of sets.py. The changes were simple, but I
may have made a mistake here or there, and since the unit tests depend on
generators, it was too much trouble to try to test the module this way. I'd
appreciate any help on testing it more thoroughly. So far, everything seems
to be working fine.

The majority of the changes were due to the new iterator protocol,
lack of generators and itertools, and dictionaries not supporting "x in d".

To use this diff, copy sets.py from the standard Python 2.3 library location
to a directory where you have saved the following code as "sets.py.di ff"
and type the following:

$ patch < sets.py.diff

Your copy of sets.py should be ready to go.

Enjoy,
Dave

--- /usr/lib/python2.3/sets.py 2003-10-09 09:05:40.001000 000 -0700
+++ sets.py 2003-12-10 15:34:14.655250 000 -0700
@@ -54,29 +54,15 @@
# - Raymond Hettinger added a number of speedups and other
# improvements.

-from __future__ import generators
-try:
- from itertools import ifilter, ifilterfalse
-except ImportError:
- # Code to make the module run under Py2.2
- def ifilter(predica te, iterable):
- if predicate is None:
- def predicate(x):
- return x
- for x in iterable:
- if predicate(x):
- yield x
- def ifilterfalse(pr edicate, iterable):
- if predicate is None:
- def predicate(x):
- return x
- for x in iterable:
- if not predicate(x):
- yield x
+from __future__ import nested_scopes
+def filterfalse(fun c, seq):
+ return filter(lambda elt: not func(elt), seq)
+False = 0
+True = not False

__all__ = ['BaseSet', 'Set', 'ImmutableSet']

-class BaseSet(object) :
+class BaseSet:
"""Common base class for mutable and immutable sets."""

__slots__ = ['_data']
@@ -90,7 +76,7 @@
raise TypeError, ("BaseSet is an abstract class. "
"Use Set or ImmutableSet.")

- # Standard protocols: __len__, __repr__, __str__, __iter__
+ # Standard protocols: __len__, __repr__, __str__, __getitem__

def __len__(self):
"""Return the number of elements of a set."""
@@ -112,12 +98,8 @@
elements.sort()
return '%s(%r)' % (self.__class__ .__name__, elements)

- def __iter__(self):
- """Return an iterator over the elements or a set.
-
- This is the keys iterator for the underlying dict.
- """
- return self._data.iter keys()
+ def __getitem__(sel f, index):
+ return self._data.keys ()[index]

# Three-way comparison is not supported. However, because __eq__ is
# tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and
@@ -176,7 +158,7 @@
memo[id(self)] = result
data = result._data
value = True
- for elt in self:
+ for elt in self._data.keys ():
data[deepcopy(elt, memo)] = value
return result

@@ -227,7 +209,7 @@
little, big = self, other
else:
little, big = other, self
- common = ifilter(big._da ta.has_key, little)
+ common = filter(big._dat a.has_key, little._data.ke ys())
return self.__class__( common)

def __xor__(self, other):
@@ -252,9 +234,9 @@
otherdata = other._data
except AttributeError:
otherdata = Set(other)._dat a
- for elt in ifilterfalse(ot herdata.has_key , selfdata):
+ for elt in filterfalse(oth erdata.has_key, selfdata.keys() ):
data[elt] = value
- for elt in ifilterfalse(se lfdata.has_key, otherdata):
+ for elt in filterfalse(sel fdata.has_key, otherdata.keys( )):
data[elt] = value
return result

@@ -279,7 +261,7 @@
except AttributeError:
otherdata = Set(other)._dat a
value = True
- for elt in ifilterfalse(ot herdata.has_key , self):
+ for elt in filterfalse(oth erdata.has_key, self._data.keys ()):
data[elt] = value
return result

@@ -291,12 +273,12 @@
(Called in response to the expression `element in self'.)
"""
try:
- return element in self._data
+ return element in self._data.keys ()
except TypeError:
transform = getattr(element , "__as_temporari ly_immutable__" , None)
if transform is None:
raise # re-raise the TypeError exception we caught
- return transform() in self._data
+ return transform() in self._data.keys ()

# Subset and superset test

@@ -305,7 +287,7 @@
self._binary_sa nity_check(othe r)
if len(self) > len(other): # Fast check for obvious cases
return False
- for elt in ifilterfalse(ot her._data.has_k ey, self):
+ for elt in filterfalse(oth er._data.has_ke y, self._data.keys ()):
return False
return True

@@ -314,7 +296,7 @@
self._binary_sa nity_check(othe r)
if len(self) < len(other): # Fast check for obvious cases
return False
- for elt in ifilterfalse(se lf._data.has_ke y, other):
+ for elt in filterfalse(sel f._data.has_key , other._data.key s()):
return False
return True

@@ -360,31 +342,14 @@

value = True

- if type(iterable) in (list, tuple, xrange):
- # Optimized: we know that __iter__() and next() can't
- # raise TypeError, so we can move 'try:' out of the loop.
- it = iter(iterable)
- while True:
- try:
- for element in it:
- data[element] = value
- return
- except TypeError:
- transform = getattr(element , "__as_immutable __", None)
- if transform is None:
- raise # re-raise the TypeError exception we caught
- data[transform()] = value
- else:
- # Safe: only catch TypeError where intended
- for element in iterable:
- try:
- data[element] = value
- except TypeError:
- transform = getattr(element , "__as_immutable __", None)
- if transform is None:
- raise # re-raise the TypeError exception we caught
- data[transform()] = value
-
+ for element in iterable:
+ try:
+ data[element] = value
+ except TypeError:
+ transform = getattr(element , "__as_immutable __", None)
+ if transform is None:
+ raise # re-raise the TypeError exception we caught
+ data[transform()] = value

class ImmutableSet(Ba seSet):
"""Immutabl e set class."""
@@ -476,8 +441,8 @@
value = True
if not isinstance(othe r, BaseSet):
other = Set(other)
- for elt in other:
- if elt in data:
+ for elt in other._data.key s():
+ if elt in data.keys():
del data[elt]
else:
data[elt] = value
@@ -493,7 +458,7 @@
data = self._data
if not isinstance(othe r, BaseSet):
other = Set(other)
- for elt in ifilter(data.ha s_key, other):
+ for elt in filter(data.has _key, other._data.key s()):
del data[elt]

# Python dict-like mass mutations: update, clear
Jul 18 '05 #1
0 1318

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4512
by: Michael Chermside | last post by:
Ype writes: > For the namespaces in Jython this 'Python internal thread safety' > is handled by the Java class: > > http://www.jython.org/docs/javadoc/org/python/core/PyStringMap.html > > which has almost all of it public methods Java synchronized: > > http://cvs.sourceforge.net/viewcvs.py/jython/jython/org/python/core/PyStringMap.
4
3418
by: angel | last post by:
A java runtime environment includes jvm and java class (for example classes.zip in sun jre). Of course jython need jvm,but does it need java class. Thanx
1
2282
by: scott | last post by:
I installed darwinports and did a "sudo port install jython" ------------------------- scott$ which jython /opt/local/bin/jython ------------------------- Jython works in interactive mode as shown below:
12
5904
by: Mark Fink | last post by:
I wrote a Jython class that inherits from a Java class and (thats the plan) overrides one method. Everything should stay the same. If I run this nothing happens whereas if I run the Java class it says: usage: java fit.FitServer host port socketTicket -v verbose I think this is because I do not understand the jython mechanism for...
3
2561
by: Sloan.Kohler | last post by:
Is Jython development dead or has it just seemed that way for over a year?. The jython.org website has a recent new appearance (but no new content) and there is some message traffic on the developer site at Sourceforge. However nothing has been released for over a year (i.e. no support for Python 2.3, 2.4 or 2.5). Is seems that IronPython...
0
293
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 356 open ( -1) / 3756 closed (+11) / 4112 total (+10) Bugs : 968 open (+10) / 6673 closed (+16) / 7641 total (+26) RFE : 254 open ( +3) / 282 closed ( +2) / 536 total ( +5) New / Reopened Patches ______________________
5
329
by: Alan Isaac | last post by:
This is an attempt to synthesize Bill and Carsten's proposals. (I'm changing the subject line to better match the topic.) http://docs.python.org/lib/typesmapping.html: for footnote (3) Keys and values are listed in an arbitrary order. This order is indeterminate and generally depends on factors outside the scope of the containing...
4
2038
by: Neil Wallace | last post by:
Hi all, I am a novice Python/Jython programmer, and Ubuntu user. Ubuntu still only supports only version 2.1 of Jython. I have used the GUI installer of Jython 2.2, and installed it to the default /root/jython2.2 directory. The install went without issues. However, typing ............jython --version in a teminal still gives me ...
5
3600
by: sarup26 | last post by:
Hello .. I would like to know more about Python and Jython? What is the difference between both of them? What is the future for Jython and which are the areas where it is used? Swot
0
7775
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8120
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7868
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6515
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5338
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3778
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1382
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1107
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.