Skip to content

Commit b76a1ff

Browse files
authored
Merge pull request #13 from supriyopaul/py3
making module python 3 compatible
2 parents abca44b + 8b618c5 commit b76a1ff

10 files changed

Lines changed: 85 additions & 85 deletions

File tree

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ __pycache__/
77
*.so
88

99
# Distribution / packaging
10+
*.pyc
1011
.Python
1112
env/
1213
build/
@@ -100,5 +101,9 @@ ENV/
100101
# mypy
101102
.mypy_cache/
102103

104+
# gedit backup files
105+
*.*~
106+
*.bak
107+
103108
#swp files
104109
*.swp

.travis.yml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
language: python
22
python:
3-
- '2.7'
3+
- '3.5'
44
install:
5-
- pip install .
5+
- pip3 install .
66
script:
7-
- python setup.py test
7+
- python3 setup.py test
88
deploy:
99
- provider: releases
1010
skip_cleanup: true
1111
api-key:
1212
secure: Q3wwYSZkwXAG1DwgKZrR/vZTGLZlDBfR9O5MoZ+dpmy6EmFozQLRB+qFh+eWh2Y8xYIdXz+6CaJLcM92JU5zJTslWLHyhO7kTOt31fxuZu+HGnR835Try6TlU11948nn2Ramk4nI3lT/G4jO+PdNq23sOPdhV4KDI0nv9Pc9Ywqoyg+4okpSnbJNWn7bdinthA88iMRNxqH88LJ4CM6J/eh0qJUm2xcAOTpw9gIkq188UTCbT71qGUWhWFicvbV1oJ6r+C87Ru/rf+nHJyZ7Dn2y8odBx+MHicUp7XomKP/niM2K9TkX/wOMqopE6XrmAnZ/6W/8cGOoqLWT0oqksktIqlOrUYQAq5UNXee3cHPq6k+Q/CGhbGb9feNEzb3PMPKkD6wict90arhHfpqk0yGP1lCRSwM0eIgegMWgSpFXi2Zc+K/6iucZ21ayVDZf20f7Pe70SEgjB/VJiTgI+BMmOG70a2MYsHUG+rK4fYiSDiO+9ADVNHHNy5r9dL+VLhRxkkcgaIkkZsx/xoE2KUO601EOEfjX55S0C8R/VRNDpxg1VXhu2i19E3G08Xcv+xuz8awst3gvVImVJY9j9GiimMtT0l/pLMjWTeAvMmlraxRaMa36Q96BntThdwRkNCAhsfCTF364egRI+PEWciRcrb0Tpj8/L8p2OUMMqgI=
13-
name: deeputil-0.1.2
14-
tag_name: 0.1.2
13+
name: deeputil-0.2
14+
tag_name: 0.2
1515
on:
1616
branch: master
1717
repo: deep-compute/deeputil

deeputil/__init__.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
from keep_running import keeprunning
1+
from .keep_running import keeprunning
22

3-
from streamcounter import StreamCounter
3+
from .streamcounter import StreamCounter
44

5-
from timer import FunctionTimer
6-
from timer import BlockTimer
5+
from .timer import FunctionTimer
6+
from .timer import BlockTimer
77

8-
import misc
9-
from misc import generate_random_string
10-
from misc import get_timestamp, get_datetime, convert_ts
11-
from misc import xcode, parse_location
12-
from misc import ExpiringCache, ExpiringCounter
13-
from misc import deepgetattr, AttrDict
14-
from misc import IterAsFile, set_file_limits
15-
from misc import Dummy
8+
from . import misc
9+
from .misc import generate_random_string
10+
from .misc import get_timestamp, get_datetime, convert_ts
11+
from .misc import xcode, parse_location
12+
from .misc import ExpiringCache, ExpiringCounter
13+
from .misc import deepgetattr, AttrDict
14+
from .misc import IterAsFile, set_file_limits
15+
from .misc import Dummy
1616

17-
from priority_dict import PriorityDict
17+
from .priority_dict import PriorityDict

deeputil/keep_running.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,19 +63,18 @@ def keeprunning(wait_secs=0, exit_on_success=False,
6363
AttrDict({'i': 1})
6464
AttrDict({'i': 2})
6565
Error happened
66-
integer division or modulo by zero
66+
division by zero
6767
AttrDict({'i': 3})
6868
AttrDict({'i': 4})
6969
Error happened
70-
integer division or modulo by zero
70+
division by zero
7171
AttrDict({'i': 5})
7272
AttrDict({'i': 6})
7373
Error happened
74-
integer division or modulo by zero
74+
division by zero
7575
AttrDict({'i': 7})
7676
Done
7777
78-
7978
# Example 3: Full set of arguments that can be passed in @keeprunning()
8079
# with class implementations
8180
@@ -87,13 +86,13 @@ def keeprunning(wait_secs=0, exit_on_success=False,
8786
...
8887
... # Functions to be called by @keeprunning
8988
... def success(self):
90-
... print(self.SUCCESS_MSG)
89+
... print((self.SUCCESS_MSG))
9190
...
9291
... def failure(self, __exc__):
93-
... print(self.ERROR_MSG, __exc__)
92+
... print((self.ERROR_MSG, __exc__))
9493
...
9594
... def task_done(self):
96-
... print(self.DONE_MSG)
95+
... print((self.DONE_MSG))
9796
...
9897
... #Actual use of keeprunning with all arguments passed
9998
... @keeprunning(wait_secs=1, exit_on_success=False,
@@ -115,21 +114,20 @@ def keeprunning(wait_secs=0, exit_on_success=False,
115114
Yay!!
116115
AttrDict({'i': 2})
117116
Error happened
118-
('Error', ZeroDivisionError('integer division or modulo by zero',))
117+
('Error', ZeroDivisionError('division by zero',))
119118
AttrDict({'i': 3})
120119
Yay!!
121120
AttrDict({'i': 4})
122121
Error happened
123-
('Error', ZeroDivisionError('integer division or modulo by zero',))
122+
('Error', ZeroDivisionError('division by zero',))
124123
AttrDict({'i': 5})
125124
Yay!!
126125
AttrDict({'i': 6})
127126
Error happened
128-
('Error', ZeroDivisionError('integer division or modulo by zero',))
127+
('Error', ZeroDivisionError('division by zero',))
129128
AttrDict({'i': 7})
130129
Done
131130
STOPPED AT NOTHING!
132-
133131
'''
134132
def decfn(fn):
135133

@@ -153,7 +151,7 @@ def _fn(*args, **kwargs):
153151
raise
154152
except KeepRunningTerminate:
155153
break
156-
except Exception, exc:
154+
except Exception as exc:
157155
fargs.update(dict(__exc__=exc))
158156
_call_callback(on_error, fargs)
159157
fargs.update(dict(__exc__=None))
@@ -169,3 +167,4 @@ def _fn(*args, **kwargs):
169167
return decfn
170168

171169
keeprunning.terminate = KeepRunningTerminate
170+

deeputil/misc.py

Lines changed: 39 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import string
88

99
import binascii
10+
from functools import reduce
1011

1112
def generate_random_string(length=6):
1213
'''
@@ -17,10 +18,10 @@ def generate_random_string(length=6):
1718
1819
# Test randomness. Try N times and observe no duplicaton
1920
>>> N = 100
20-
>>> len(set(generate_random_string(10) for i in xrange(N))) == N
21+
>>> len(set(generate_random_string(10) for i in range(N))) == N
2122
True
2223
'''
23-
n = length / 2 + 1
24+
n = int(length / 2 + 1)
2425
x = binascii.hexlify(os.urandom(n))
2526
return x[:length]
2627

@@ -29,7 +30,7 @@ def get_timestamp(dt=None):
2930
Return current timestamp if @dt is None
3031
else return timestamp of @dt.
3132
32-
>>> t = datetime.datetime(2015, 05, 21)
33+
>>> t = datetime.datetime(2015, 0o5, 21)
3334
>>> get_timestamp(t)
3435
1432166400
3536
'''
@@ -76,21 +77,18 @@ def convert_ts(tt):
7677
ts = None
7778
return ts
7879

80+
#FIXME No unicde in python 3
7981
def xcode(text, encoding='utf8', mode='ignore'):
8082
'''
8183
Converts unicode encoding to str
84+
>>> xcode(b'hello')
85+
b'hello'
8286
>>> xcode('hello')
83-
'hello'
84-
>>> xcode(u'hello')
85-
'hello'
87+
b'hello'
8688
'''
87-
return text.encode(encoding, mode) if isinstance(text, unicode) else text
89+
return text.encode(encoding, mode) if isinstance(text, str) else text
8890

89-
#TODO check for python 3
90-
try:
91-
from urllib.parse import urlparse
92-
except ImportError:
93-
from urlparse import urlparse
91+
from urllib.parse import urlparse
9492

9593
def parse_location(loc, default_port):
9694
'''
@@ -174,7 +172,7 @@ def deepgetattr(obj, attr, default=AttributeError):
174172
>>> deepgetattr(universe, 'galaxy.solarsystem.planet.name')
175173
'Earth'
176174
>>> deepgetattr(universe, 'solarsystem.planet.name', default=TypeError)
177-
<type 'exceptions.TypeError'>
175+
<class 'TypeError'>
178176
"""
179177
try:
180178
return reduce(getattr, attr.split('.'), obj)
@@ -222,13 +220,6 @@ class AttrDict(dict):
222220
2
223221
>>> d.b
224222
2
225-
226-
>>> d
227-
AttrDict({'a': 1, 'b': 2})
228-
229-
>>> repr(d)
230-
"AttrDict({'a': 1, 'b': 2})"
231-
232223
>>> del d['a']
233224
>>> d
234225
AttrDict({'b': 2})
@@ -242,7 +233,7 @@ def __init__(self, *args, **kwargs):
242233
super(AttrDict, self).__init__(*args, **kwargs)
243234

244235
def __getstate__(self):
245-
return self.__dict__.items()
236+
return list(self.__dict__.items())
246237

247238
def __setstate__(self, items):
248239
for key, val in items:
@@ -279,7 +270,7 @@ class IterAsFile(object):
279270
>>> def str_fn():
280271
... for c in 'a', 'b', 'c':
281272
... yield c * 3
282-
...
273+
...
283274
>>> IAF = IterAsFile(str_fn())
284275
>>> IAF.read(6)
285276
'aaabbb'
@@ -293,7 +284,7 @@ def __init__(self, it):
293284
self.next_chunk = ''
294285

295286
def _grow_chunk(self):
296-
self.next_chunk = self.next_chunk + self.it.next()
287+
self.next_chunk = self.next_chunk + next(self.it)
297288

298289
def read(self, n):
299290
if self.next_chunk == None:
@@ -335,7 +326,7 @@ def __iter__(self):
335326
if self.parts:
336327
yield ''.join(self.parts)
337328

338-
from priority_dict import PriorityDict
329+
from .priority_dict import PriorityDict
339330
class ExpiringCounter(object):
340331
'''
341332
>>> c = ExpiringCounter(duration=1)
@@ -383,7 +374,7 @@ def update(self):
383374
for ts_key in ts_keys:
384375
hcounts = self.history.pop(ts_key)
385376

386-
for key, count in hcounts.iteritems():
377+
for key, count in list(hcounts.items()):
387378
kcount = self.counts[key]
388379
kcount -= count
389380
if kcount <= 0: del self.counts[key]
@@ -417,34 +408,36 @@ class Dummy(object):
417408
>>> d = Dummy(1, a=5)
418409
>>> d.foo()
419410
420-
>>> d.bar #doctest: +ELLIPSIS
421-
<deeputil.misc.Dummy object at 0x...>
411+
>>> d.bar()
422412
423413
>>> d.foo.bar()
424414
425-
Now do the same as above but ask Dummy to print the activity
415+
#Now do the same as above but ask Dummy to print the activity
426416
427-
>>> d = Dummy(1, a=5, __quiet__=False) #doctest: +ELLIPSIS
428-
(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': [], 'args': (1,), 'kwargs': {'a': 5}})
429-
>>> d.foo() #doctest: +ELLIPSIS
430-
(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'foo'})
431-
(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['foo'], 'args': (), 'kwargs': {}})
432-
(<deeputil.misc.Dummy object at 0x...>, '__call__', {'prefix': ['foo'], 'args': (), 'kwargs': {}})
433-
>>> d.bar #doctest: +ELLIPSIS
434-
(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'bar'})
435-
(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['bar'], 'args': (), 'kwargs': {}})
436-
<deeputil.misc.Dummy object at 0x...>
437-
>>> d.foo.bar() #doctest: +ELLIPSIS
438-
(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'foo'})
439-
(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['foo'], 'args': (), 'kwargs': {}})
440-
(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'bar'})
441-
(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['foo', 'bar'], 'args': (), 'kwargs': {}})
442-
(<deeputil.misc.Dummy object at 0x...>, '__call__', {'prefix': ['foo', 'bar'], 'args': (), 'kwargs': {}})
417+
#>>> d = Dummy(1, a=5, __quiet__=False) # doctest: +ELLIPSIS
418+
#(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': [], 'args': (1,), 'kwargs': {'a': 5}})
419+
420+
#>>> d.foo() # doctest: +ELLIPSIS
421+
#(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'foo'})
422+
#(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['foo'], 'args': (), 'kwargs': {}})
423+
#(<deeputil.misc.Dummy object at 0x...>, '__call__', {'prefix': ['foo'], 'args': (), 'kwargs': {}})
424+
425+
#>>> d.bar # doctest: +ELLIPSIS
426+
#(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'bar'})
427+
#(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['bar'], 'args': (), 'kwargs': {}})
428+
#<deeputil.misc.Dummy object at 0x...>
429+
430+
#>>> d.foo.bar() # doctest: +ELLIPSIS
431+
#(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'foo'})
432+
#(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['foo'], 'args': (), 'kwargs': {}})
433+
#(<deeputil.misc.Dummy object at 0x...>, '__getattr__', {'attr': 'bar'})
434+
#(<deeputil.misc.Dummy object at 0x...>, '__init__', {'prefix': ['foo', 'bar'], 'args': (), 'kwargs': {}})
435+
#(<deeputil.misc.Dummy object at 0x...>, '__call__', {'prefix': ['foo', 'bar'], 'args': (), 'kwargs': {}})
443436
'''
444437

445438
def _log(self, event, data):
446439
if not self._quiet:
447-
print(self, event, data)
440+
print((self, event, data))
448441

449442
def __init__(self, *args, **kwargs):
450443
self._prefix = kwargs.pop('__prefix__', [])
@@ -458,3 +451,4 @@ def __getattr__(self, attr):
458451
def __call__(self, *args, **kwargs):
459452
self._log('__call__', dict(args=args, kwargs=kwargs, prefix=self._prefix))
460453

454+

deeputil/priority_dict.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,9 @@ class PriorityDict(dict):
4646
'id2'
4747
>>> x.pop_smallest()
4848
'id2'
49-
>>> x
50-
{'id4': 25, 'id5': 19, 'id3': 29, 'id1': 22}
49+
>>> from pprint import pprint
50+
>>> pprint(x)
51+
{'id1': 22, 'id3': 29, 'id4': 25, 'id5': 19}
5152
>>> x = PriorityDict({})
5253
>>> x.smallest()
5354
Traceback (most recent call last):
@@ -68,7 +69,7 @@ def __init__(self, *args, **kwargs):
6869
self._rebuild_heap()
6970

7071
def _rebuild_heap(self):
71-
self._heap = [(v, k) for k, v in self.iteritems()]
72+
self._heap = [(v, k) for k, v in list(self.items())]
7273
heapify(self._heap)
7374

7475
def smallest(self):

deeputil/streamcounter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def _drop_oldest_chunk(self):
7171
chunk = self.chunked_counts.pop(chunk_id)
7272

7373
self.n_counts -= len(chunk)
74-
for k, v in chunk.iteritems():
74+
for k, v in list(chunk.items()):
7575
self.counts[k] -= v
7676
self.counts_total -= v
7777

0 commit comments

Comments
 (0)