Refactor to run in both Python 2.7 and Python 3.6

Refactor to run in both Python 2.7 and Python 3.6. This is important as
python 2.7 is end of life.

I tried to edit as few things as possible in this commit to minimize
conflicts which means the code could be prettier.

Signed-off-by: Viktor Sjölind <viktor@sjolind.se>
This commit is contained in:
Viktor Sjölind 2017-06-09 15:19:24 +02:00 committed by Jonatan Pålsson
parent 2125b2d739
commit 96e6da2752
5 changed files with 80 additions and 74 deletions

View file

@ -25,7 +25,14 @@ write simpler bots.
"""
import sys
from UserDict import UserDict
# UserDict is moved to collections in Python3
# In order to support Python 2.7 this has to be imported
# in the following way
try:
from UserDict import UserDict
except ImportError:
from collections import UserDict
from irclib import SimpleIRCClient
from irclib import nm_to_n, irc_lower, all_events
@ -160,7 +167,7 @@ class SingleServerIRCBot(SimpleIRCClient):
"""[Internal]"""
before = nm_to_n(e.source())
after = e.target()
for ch in self.channels.values():
for ch in list(self.channels.values()):
if ch.has_user(before):
ch.change_nick(before, after)
@ -177,7 +184,7 @@ class SingleServerIRCBot(SimpleIRCClient):
def _on_quit(self, c, e):
"""[Internal]"""
nick = nm_to_n(e.source())
for ch in self.channels.values():
for ch in list(self.channels.values()):
if ch.has_user(nick):
ch.remove_user(nick)
@ -283,8 +290,6 @@ class IRCDict:
del self.canon_keys[ck]
def __iter__(self):
return iter(self.data)
def __contains__(self, key):
return self.has_key(key)
def clear(self):
self.data.clear()
self.canon_keys.clear()
@ -294,15 +299,15 @@ class IRCDict:
import copy
return copy.copy(self)
def keys(self):
return self.data.keys()
return list(self.data.keys())
def items(self):
return self.data.items()
return list(self.data.items())
def values(self):
return self.data.values()
return list(self.data.values())
def has_key(self, key):
return irc_lower(key) in self.canon_keys
def update(self, dict):
for k, v in dict.items():
for k, v in list(dict.items()):
self.data[k] = v
def get(self, key, failobj=None):
return self.data.get(key, failobj)
@ -322,16 +327,16 @@ class Channel:
def users(self):
"""Returns an unsorted list of the channel's users."""
return self.userdict.keys()
return list(self.userdict.keys())
def opers(self):
"""Returns an unsorted list of the channel's operators."""
return self.operdict.keys()
return list(self.operdict.keys())
def voiced(self):
"""Returns an unsorted list of the persons that have voice
mode set in the channel."""
return self.voiceddict.keys()
return list(self.voiceddict.keys())
def has_user(self, nick):
"""Check whether the channel has a user."""