473,789 Members | 2,561 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 1331

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

Similar topics

4
4565
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
3427
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
2297
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
5928
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 inheritance (yet).
3
2575
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 may have a better future than Jython. I know this is a bit of a troll but I'm concerned about...
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 program. However, if items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called...
4
2045
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 ........ Jython 2.1 on java (JIT: null)
5
3611
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
9506
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10193
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10136
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
7525
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6761
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5415
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4089
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2906
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.