diff --git a/src/chat_control.py b/src/chat_control.py
index 6c0976ea5e0ec77f4509f868869d3cab12a6b45c..dfa8beef503ddc45cf253ba7f46eef59854a4025 100644
--- a/src/chat_control.py
+++ b/src/chat_control.py
@@ -297,7 +297,7 @@ class ChatControlBase(MessageControl):
 				if lang:
 					self.msg_textview.lang = lang
 					spell.set_language(lang)
-			except (gobject.GError, RuntimeError), msg:
+			except (gobject.GError, RuntimeError):
 				dialogs.AspellDictError(lang)
 		self.conv_textview.tv.show()
 		self._paint_banner()
@@ -438,7 +438,6 @@ class ChatControlBase(MessageControl):
 	def show_emoticons_menu(self):
 		if not gajim.config.get('emoticons_theme'):
 			return
-		msg_tv = self.msg_textview
 		def set_emoticons_menu_position(w, msg_tv = self.msg_textview):
 			window = msg_tv.get_window(gtk.TEXT_WINDOW_WIDGET)
 			# get the window position
@@ -452,7 +451,7 @@ class ChatControlBase(MessageControl):
 				cursor.x, cursor.y)
 			x = origin[0] + cursor[0]
 			y = origin[1] + size[1]
-			menu_width, menu_height = gajim.interface.emoticons_menu.size_request()
+			menu_height = gajim.interface.emoticons_menu.size_request()[1]
 			#FIXME: get_line_count is not so good
 			#get the iter of cursor, then tv.get_line_yrange
 			# so we know in which y we are typing (not how many lines we have
@@ -1189,7 +1188,7 @@ class ChatControl(ChatControlBase):
 			if session:
 				# Don't use previous session if we want to a specific resource
 				# and it's not the same
-				j, r = gajim.get_room_and_nick_from_fjid(str(session.jid))
+				r = gajim.get_room_and_nick_from_fjid(str(session.jid))[1]
 				if resource and resource != r:
 					session = None
 
@@ -1505,7 +1504,6 @@ class ChatControl(ChatControlBase):
 
 		banner_name_label = self.xml.get_widget('banner_name_label')
 		banner_name_tooltip = gtk.Tooltips()
-		banner_eventbox = self.xml.get_widget('banner_eventbox')
 
 		name = contact.get_shown_name()
 		if self.resource:
@@ -1908,7 +1906,6 @@ class ChatControl(ChatControlBase):
 		if contact is set to print_queue: it is incomming from queue
 		if contact is not set: it's an incomming message'''
 		contact = self.contact
-		jid = contact.jid
 
 		if frm == 'status':
 			if not gajim.config.get('print_status_in_chats'):
@@ -2297,7 +2294,7 @@ class ChatControl(ChatControlBase):
 			def on_cancel():
 				on_no(self)
 
-			dialog = dialogs.ConfirmationDialog(
+			dialogs.ConfirmationDialog(
 				# %s is being replaced in the code with JID
 				_('You just received a new message from "%s"') % self.contact.jid,
 				_('If you close this tab and you have history disabled, '\
@@ -2388,7 +2385,6 @@ class ChatControl(ChatControlBase):
 		path = treeview.get_selection().get_selected_rows()[1][0]
 		iter = model.get_iter(path)
 		type = model[iter][2]
-		account = model[iter][4].decode('utf-8')
 		if type != 'contact': # source is not a contact
 			return
 		dropped_jid = data.decode('utf-8')
diff --git a/src/common/commands.py b/src/common/commands.py
index bbe5385f927e3350e31263005423cb358524a051..73f9d521ef6b7bbeebadd4fe467abc376cfb827a 100644
--- a/src/common/commands.py
+++ b/src/common/commands.py
@@ -71,7 +71,7 @@ class AdHocCommand:
 			' bad-request'))
 
 	def cancel(self, request):
-		response, cmd = self.buildResponse(request, status = 'canceled')
+		response = self.buildResponse(request, status = 'canceled')[0]
 		self.connection.connection.send(response)
 		return False	# finish the session
 
diff --git a/src/common/connection.py b/src/common/connection.py
index 996c25575d108a92aaceb8d1e6008260e52abd98..a3b459629ae8673fda47f91d3e3d50fd4038e021 100644
--- a/src/common/connection.py
+++ b/src/common/connection.py
@@ -413,7 +413,6 @@ class Connection(ConnectionHandlers):
 
 		if data:
 			hostname = data['hostname']
-			usessl = data['usessl']
 			self.try_connecting_for_foo_secs = 45
 			p = data['proxy']
 			use_srv = True
@@ -959,7 +958,6 @@ class Connection(ConnectionHandlers):
 		sshow = helpers.get_xmpp_show(show)
 		if not msg:
 			msg = ''
-		keyID = gajim.config.get_per('accounts', self.name, 'keyid')
 		if show == 'offline':
 			p = common.xmpp.Presence(typ = 'unavailable', to = jid)
 			p = self.add_sha(p, False)
@@ -983,7 +981,6 @@ class Connection(ConnectionHandlers):
 		sshow = helpers.get_xmpp_show(show)
 		if not msg:
 			msg = ''
-		keyID = gajim.config.get_per('accounts', self.name, 'keyid')
 		sign_msg = False
 		if not auto and not show == 'offline':
 			sign_msg = True
@@ -1401,7 +1398,7 @@ class Connection(ConnectionHandlers):
 			return
 		iq = common.xmpp.Iq(typ='get')
 		iq2 = iq.addChild(name='query', namespace=common.xmpp.NS_PRIVATE)
-		iq3 = iq2.addChild(name='gajim', namespace='gajim:prefs')
+		iq2.addChild(name='gajim', namespace='gajim:prefs')
 		self.connection.send(iq)
 
 	def get_bookmarks(self):
@@ -1431,11 +1428,11 @@ class Connection(ConnectionHandlers):
 			# Note: need to handle both None and '' as empty
 			#   thus shouldn't use "is not None"
 			if bm.get('nick', None):
-				iq5 = iq4.setTagData('nick', bm['nick'])
+				iq4.setTagData('nick', bm['nick'])
 			if bm.get('password', None):
-				iq5 = iq4.setTagData('password', bm['password'])
+				iq4.setTagData('password', bm['password'])
 			if bm.get('print_status', None):
-				iq5 = iq4.setTagData('print_status', bm['print_status'])
+				iq4.setTagData('print_status', bm['print_status'])
 		self.connection.send(iq)
 
 	def get_annotations(self):
@@ -1707,7 +1704,7 @@ class Connection(ConnectionHandlers):
 			if gajim.account_is_connected(self.name):
 				hostname = gajim.config.get_per('accounts', self.name, 'hostname')
 				iq = common.xmpp.Iq(typ = 'set', to = hostname)
-				q = iq.setTag(common.xmpp.NS_REGISTER + ' query').setTag('remove')
+				iq.setTag(common.xmpp.NS_REGISTER + ' query').setTag('remove')
 				con.send(iq)
 				on_remove_success(True)
 				return
diff --git a/src/common/connection_handlers.py b/src/common/connection_handlers.py
index a8471b1c825fc835ac929229c58940bc8944f0e3..6bae049d510d2ae3a2085536241629d3a71556b2 100644
--- a/src/common/connection_handlers.py
+++ b/src/common/connection_handlers.py
@@ -768,9 +768,6 @@ class ConnectionDisco:
 		if node:
 			q.setAttr('node', node)
 		q.addChild('identity', attrs = gajim.gajim_identity)
-		extension = None
-		if node and node.find('#') != -1:
-			extension = node[node.index('#') + 1:]
 		client_version = 'http://gajim.org#' + gajim.caps_hash[self.name]
 
 		if node in (None, client_version):
@@ -984,7 +981,7 @@ class ConnectionVcard:
 			j = gajim.get_jid_from_account(self.name)
 		self.awaiting_answers[id] = (VCARD_ARRIVED, j, groupchat_jid)
 		if groupchat_jid:
-			room_jid, nick = gajim.get_room_and_nick_from_fjid(groupchat_jid)
+			room_jid = gajim.get_room_and_nick_from_fjid(groupchat_jid)[0]
 			if not room_jid in self.room_jids:
 				self.room_jids.append(room_jid)
 			self.groupchat_jids[id] = groupchat_jid
@@ -1395,6 +1392,7 @@ class ConnectionHandlers(ConnectionVcard, ConnectionBytestream, ConnectionDisco,
 		try:
 			idle.init()
 		except Exception:
+			global HAS_IDLE
 			HAS_IDLE = False
 
 		self.gmail_last_tid = None
diff --git a/src/common/helpers.py b/src/common/helpers.py
index aa2184b6d732dbf6c6aed1015443d358097c156a..9fe6dd79537acb121c647728a257b7dc653c625b 100644
--- a/src/common/helpers.py
+++ b/src/common/helpers.py
@@ -1032,7 +1032,7 @@ def get_notification_icon_tooltip_dict():
 def get_notification_icon_tooltip_text():
 	text = None
 	# How many events must there be before they're shown summarized, not per-user
-	max_ungrouped_events = 10
+	# max_ungrouped_events = 10
 	# Character which should be used to indent in the tooltip.
 	indent_with = ' '
 
diff --git a/src/common/logger.py b/src/common/logger.py
index 21377c761a6ab72f9b95eed2cfa6847302efba6d..a8582bca38b5e6edfc6a0740a682e9424c274498 100644
--- a/src/common/logger.py
+++ b/src/common/logger.py
@@ -178,7 +178,7 @@ class Logger:
 		and after that all okay'''
 		
 		if jid.find('/') > -1: 
-			possible_room_jid, possible_nick = jid.split('/', 1)
+			possible_room_jid = jid.split('/', 1)[1]
 			return self.jid_is_room_jid(possible_room_jid)
 		else:
 			# it's not a full jid, so it's not a pm one
@@ -480,7 +480,7 @@ class Logger:
 		returns a list of tupples containg time, kind, message,
 		list with empty tupple if nothing found to meet our demands'''
 		try:
-			jid_id = self.get_jid_id(jid)
+			self.get_jid_id(jid)
 		except exceptions.PysqliteOperationalError, e:
 			# Error trying to create a new jid_id. This means there is no log
 			return []
@@ -522,7 +522,7 @@ class Logger:
 		for each row in a list of tupples,
 		returns list with empty tupple if we found nothing to meet our demands'''
 		try:
-			jid_id = self.get_jid_id(jid)
+			self.get_jid_id(jid)
 		except exceptions.PysqliteOperationalError, e:
 			# Error trying to create a new jid_id. This means there is no log
 			return []
@@ -547,7 +547,7 @@ class Logger:
 		for each row in a list of tupples,
 		returns list with empty tupple if we found nothing to meet our demands'''
 		try:
-			jid_id = self.get_jid_id(jid)
+			self.get_jid_id(jid)
 		except exceptions.PysqliteOperationalError, e:
 			# Error trying to create a new jid_id. This means there is no log
 			return []
@@ -574,7 +574,7 @@ class Logger:
 	def get_days_with_logs(self, jid, year, month, max_day, account):
 		'''returns the list of days that have logs (not status messages)'''
 		try:
-			jid_id = self.get_jid_id(jid)
+			self.get_jid_id(jid)
 		except exceptions.PysqliteOperationalError, e:
 			# Error trying to create a new jid_id. This means there is no log
 			return []
diff --git a/src/common/nslookup.py b/src/common/nslookup.py
index ca0cdc32e2c5bdcf26e21c88acd4538ce3f4f92c..748b8aca85754651feb099aa68136c18b8e78ace 100644
--- a/src/common/nslookup.py
+++ b/src/common/nslookup.py
@@ -268,7 +268,7 @@ class IdleCommand(IdleObject):
 	def pollin(self):
 		try:
 			res = self.pipe.read()
-		except Exception, e:
+		except Exception:
 			res = ''
 		if res == '':
 			return self.pollend()
diff --git a/src/common/optparser.py b/src/common/optparser.py
index 7d0f1ea4f1032e09d19a80ea6e82cb9c71504897..9b9ccd467faea3fe0ef6c5d1e18346c255ba43ca 100644
--- a/src/common/optparser.py
+++ b/src/common/optparser.py
@@ -261,7 +261,7 @@ class OptionsParser:
 			)
 			con.commit()
 			gajim.logger.init_vars()
-		except sqlite.OperationalError, e:
+		except sqlite.OperationalError:
 			pass
 		con.close()
 
@@ -333,7 +333,7 @@ class OptionsParser:
 				'''
 			)
 			con.commit()
-		except sqlite.OperationalError, e:
+		except sqlite.OperationalError:
 			pass
 		con.close()
 		gajim.config.set('version', '0.10.1.3')
@@ -454,7 +454,7 @@ class OptionsParser:
 				'''
 			)
 			con.commit()
-		except sqlite.OperationalError, e:
+		except sqlite.OperationalError:
 			pass
 		con.close()
 		gajim.config.set('version', '0.11.1.3')
@@ -496,7 +496,7 @@ class OptionsParser:
 				'''
 			)
 			con.commit()
-		except sqlite.OperationalError, e:
+		except sqlite.OperationalError:
 			pass
 		con.close()
 		gajim.config.set('version', '0.11.1.5')
@@ -532,7 +532,7 @@ class OptionsParser:
 				'''
 			)
 			con.commit()
-		except sqlite.OperationalError, e:
+		except sqlite.OperationalError:
 			pass
 		con.close()
 		gajim.config.set('version', '0.11.4.1')
@@ -569,7 +569,7 @@ class OptionsParser:
 				'''
 			)
 			con.commit()
-		except sqlite.OperationalError, e:
+		except sqlite.OperationalError:
 			pass
 		con.close()
 		gajim.config.set('version', '0.11.4.3')
@@ -583,7 +583,7 @@ class OptionsParser:
 		try:
 			cur.executescript('DROP TABLE caps_cache;')
 			con.commit()
-		except sqlite.OperationalError, e:
+		except sqlite.OperationalError:
 			pass
 		try:
 			cur.executescript(
diff --git a/src/common/passwords.py b/src/common/passwords.py
index e6e66b59355fe5faf70218fe0eb7d44e188990a0..14b1cdcd95f8e36ac364bb026b13cd1416b9e52e 100644
--- a/src/common/passwords.py
+++ b/src/common/passwords.py
@@ -67,7 +67,7 @@ class GnomePasswordStorage(PasswordStorage):
 		if conf is None:
 			return None
 		try:
-			unused, auth_token = conf.split('gnomekeyring:')
+			auth_token = conf.split('gnomekeyring:')[1]
 			auth_token = int(auth_token)
 		except ValueError:
 			password = conf
diff --git a/src/common/pep.py b/src/common/pep.py
index 19009ac572fe1cb037103b79948e8594c2a63eb1..d7d2cc48937cbf2640b54895894b24aa52747d2b 100644
--- a/src/common/pep.py
+++ b/src/common/pep.py
@@ -311,7 +311,7 @@ def user_tune(items, name, jid):
 			if 'length' in acc.tune:
 				del acc.tune['length']
 
-	(user, resource) = gajim.get_room_and_nick_from_fjid(jid)
+	user = gajim.get_room_and_nick_from_fjid(jid)[0]
 	for contact in gajim.contacts.get_contacts(name, user):
 		if has_child:
 			if 'artist' in contact.tune:
@@ -400,7 +400,7 @@ def user_activity(items, name, jid):
 			if 'text' in acc.activity:
 				del acc.activity['text']
 
-	(user, resource) = gajim.get_room_and_nick_from_fjid(jid)
+	user = gajim.get_room_and_nick_from_fjid(jid)[0]
 	for contact in gajim.contacts.get_contacts(name, user):
 		if has_child:
 			if 'activity' in contact.activity:
@@ -452,7 +452,7 @@ def user_nickname(items, name, jid):
 			gajim.nicks[name] = gajim.config.get_per('accounts',
 				name, 'name')
 
-	(user, resource) = gajim.get_room_and_nick_from_fjid(jid)
+	user = gajim.get_room_and_nick_from_fjid(jid)[0]
 	if has_child:
 		if nick is not None:
 			for contact in gajim.contacts.get_contacts(name, user):
@@ -541,7 +541,7 @@ def user_retract_nickname(account):
 	gajim.connections[account].send_pb_retract('', xmpp.NS_NICK, '0')
 
 def delete_pep(jid, name):
-	(user, resource) = gajim.get_room_and_nick_from_fjid(jid)
+	user = gajim.get_room_and_nick_from_fjid(jid)[0]
 
 	if jid == gajim.get_jid_from_account(name):
 		acc = gajim.connections[name]
diff --git a/src/common/proxy65_manager.py b/src/common/proxy65_manager.py
index c520ecb437553fb8ea59cec6ae80c21cda26a39e..652bc6e55678a95e22ff7e11af53bb85802b0a6d 100644
--- a/src/common/proxy65_manager.py
+++ b/src/common/proxy65_manager.py
@@ -279,7 +279,7 @@ class HostTester(Socks5, IdleObject):
 			self._send = self._sock.send
 			self._recv = self._sock.recv
 		except Exception, ee:
-			(errnum, errstr) = ee
+			errnum = ee[0]
 			# 56 is for freebsd
 			if errnum in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK):
 				# still trying to connect
@@ -391,7 +391,7 @@ class ReceiverTester(Socks5, IdleObject):
 			self._send = self._sock.send
 			self._recv = self._sock.recv
 		except Exception, ee:
-			(errnum, errstr) = ee
+			errnum = ee[0]
 			# 56 is for freebsd
 			if errnum in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK):
 				# still trying to connect
diff --git a/src/common/sleepy.py b/src/common/sleepy.py
index 94c8d517476443a77624c5653712eb84a83b1b7b..3f3a4c6f15fd8932aa019cde5fa332e593fd1cae 100644
--- a/src/common/sleepy.py
+++ b/src/common/sleepy.py
@@ -87,6 +87,7 @@ class SleepyWindows:
 
 class SleepyUnix:
 	def __init__(self, away_interval = 60, xa_interval = 120):
+		global SUPPORTED
 		self.away_interval = away_interval
 		self.xa_interval = xa_interval
 		self.state = STATE_AWAKE # assume we are awake
diff --git a/src/common/socks5.py b/src/common/socks5.py
index 1680bf653651adab9ec5459627512582966b1867..f45593093d7deed0e81855d51afe2ccac6b2c504 100644
--- a/src/common/socks5.py
+++ b/src/common/socks5.py
@@ -417,7 +417,7 @@ class Socks5:
 		received = ''
 		try:
 			add = self._recv(64)
-		except Exception, e:
+		except Exception:
 			add = ''
 		received += add
 		if len(add) == 0:
@@ -427,8 +427,8 @@ class Socks5:
 	def send_raw(self,raw_data):
 		''' Writes raw outgoing data. '''
 		try:
-			lenn = self._send(raw_data)
-		except Exception, e:
+			self._send(raw_data)
+		except Exception:
 			self.disconnect()
 		return len(raw_data)
 
@@ -507,7 +507,7 @@ class Socks5:
 			fd = self.get_fd()
 			try:
 				buff = self._recv(MAX_BUFF_LEN)
-			except Exception, e:
+			except Exception:
 				buff = ''
 			current_time = self.idlequeue.current_time()
 			self.file_props['elapsed-time'] += current_time - \
@@ -571,7 +571,7 @@ class Socks5:
 		mechanisms '''
 		auth_mechanisms = []
 		try:
-			ver, num_auth = struct.unpack('!BB', buff[:2])
+			num_auth = struct.unpack('!xB', buff[:2])[0]
 			for i in xrange(num_auth):
 				mechanism, = struct.unpack('!B', buff[1 + i])
 				auth_mechanisms.append(mechanism)
@@ -601,8 +601,7 @@ class Socks5:
 
 	def _parse_request_buff(self, buff):
 		try: # don't trust on what comes from the outside
-			version, req_type, reserved, host_type, = struct.unpack('!BBBB',
-				buff[:4])
+			req_type, host_type, = struct.unpack('!xBxB', buff[:4])
 			if host_type == 0x01:
 				host_arr = struct.unpack('!iiii', buff[4:8])
 				host, = '.'.join(str(s) for s in host_arr)
@@ -765,7 +764,7 @@ class Socks5Sender(Socks5, IdleObject):
 				return -1 # invalid auth methods received
 		elif self.state == 3: # get next request
 			buff = self.receive()
-			(req_type, self.sha_msg, port) = self._parse_request_buff(buff)
+			req_type, self.sha_msg = self._parse_request_buff(buff)[:2]
 			if req_type != 0x01:
 				return -1 # request is not of type 'connect'
 		self.state += 1 # go to the next step
@@ -974,7 +973,7 @@ class Socks5Receiver(Socks5, IdleObject):
 			self._send=self._sock.send
 			self._recv=self._sock.recv
 		except Exception, ee:
-			(errnum, errstr) = ee
+			errnum = ee[0]
 			self.connect_timeout += 1
 			if errnum == 111 or self.connect_timeout > 1000:
 				self.queue._connection_refused(self.streamhost,
@@ -1019,8 +1018,8 @@ class Socks5Receiver(Socks5, IdleObject):
 			sub_buff = buff[:4]
 			if len(sub_buff) < 4:
 				return None
-			version, command, rsvd, address_type = struct.unpack('!BBBB', buff[:4])
-			addrlen, address, port = 0, 0, 0
+			version, address_type = struct.unpack('!BxxB', buff[:4])
+			addrlen = 0
 			if address_type == 0x03:
 				addrlen = ord(buff[4])
 				address = struct.unpack('!%ds' % addrlen, buff[5:addrlen + 5])
diff --git a/src/common/stanza_session.py b/src/common/stanza_session.py
index dad5ac58407c2fbf8af018ee76724a624a042e76..6e3d3f06772a4c0cf2bacbf95e4aca29ee16fb86 100644
--- a/src/common/stanza_session.py
+++ b/src/common/stanza_session.py
@@ -28,6 +28,7 @@ from common import gajim
 from common import xmpp
 from common import exceptions
 
+import itertools
 import random
 import string
 
@@ -91,8 +92,8 @@ class StanzaSession(object):
 		return any_removed
 
 	def generate_thread_id(self):
-		return ''.join([random.choice(string.ascii_letters) for x in xrange(0,
-			32)])
+		return ''.join([f(string.ascii_letters) for f in itertools.repeat(
+			random.choice, 32)])
 
 	def send(self, msg):
 		if self.thread_id:
@@ -386,10 +387,9 @@ class EncryptedStanzaSession(StanzaSession):
 			parsed = xmpp.Node(node='<node>' + plaintext + '</node>')
 
 			if self.negotiated['recv_pubkey'] == 'hash':
-				fingerprint = parsed.getTagData('fingerprint')
-
+				# fingerprint = parsed.getTagData('fingerprint')
 				# XXX find stored pubkey or terminate session
-				raise 'unimplemented'
+				raise NotImplementedError()
 			else:
 				if self.negotiated['sign_algs'] == (XmlDsig + 'rsa-sha256'):
 					keyvalue = parsed.getTag(name='RSAKeyValue', namespace=XmlDsig)
@@ -771,7 +771,7 @@ class EncryptedStanzaSession(StanzaSession):
 		else:
 			srses = secrets.secrets().retained_secrets(self.conn.name,
 				self.jid.getStripped())
-			rshashes = [self.hmac(self.n_s, rs) for (rs,v) in srses]
+			rshashes = [self.hmac(self.n_s, rs[0]) for rs in srses]
 
 			if not rshashes:
 				# we've never spoken before, but we'll pretend we have
@@ -838,7 +838,8 @@ class EncryptedStanzaSession(StanzaSession):
 		rshashes = [base64.b64decode(rshash) for rshash in form.getField(
 			'rshashes').getValues()]
 
-		for (secret, verified) in srses:
+		for s in srses:
+			secret = s[0]
 			if self.hmac(self.n_o, secret) in rshashes:
 				srs = secret
 				break
@@ -889,7 +890,8 @@ class EncryptedStanzaSession(StanzaSession):
 
 		srshash = base64.b64decode(form['srshash'])
 
-		for (secret, verified) in srses:
+		for s in srses:
+			secret = s[0]
 			if self.hmac(secret, 'Shared Retained Secret') == srshash:
 				srs = secret
 				break
diff --git a/src/common/xmpp/auth.py b/src/common/xmpp/auth.py
index 9474648a3d9b25cce5bc4855eabb7dd49bec8adb..af3b86405c2761386f9fc3fee81c31101313c191 100644
--- a/src/common/xmpp/auth.py
+++ b/src/common/xmpp/auth.py
@@ -61,8 +61,14 @@ class NonSASL(PlugIn):
             token=query.getTagData('token')
             seq=query.getTagData('sequence')
             self.DEBUG("Performing zero-k authentication",'ok')
-            hash = sha.new(sha.new(self.password).hexdigest()+token).hexdigest()
-            for foo in xrange(int(seq)): hash = sha.new(hash).hexdigest()
+
+            def hasher(s):
+               return sha.new(s).hexdigest()
+
+            def hash_n_times(s, count):
+               return count and hasher(hash_n_times(s, count-1)) or s
+
+            hash = hash_n_times(hasher(hasher(self.password)+token), int(seq))
             query.setTagData('hash',hash)
             method='0k'
         else:
@@ -182,10 +188,8 @@ class SASL(PlugIn):
             resp['username']=self.username
             resp['realm']=self._owner.Server
             resp['nonce']=chal['nonce']
-            cnonce=''
-            for i in range(7):
-                cnonce+=hex(int(random.random()*65536*4096))[2:]
-            resp['cnonce']=cnonce
+            resp['cnonce'] = ''.join("%x" % randint(0, 2**28) for randint in
+                itertools.repeat(random.randint, 7))
             resp['nc']=('00000001')
             resp['qop']='auth'
             resp['digest-uri']='xmpp/'+self._owner.Server
@@ -305,4 +309,4 @@ class ComponentBind(PlugIn):
             self.DEBUG('Binding failed: timeout expired.','error')
             return ''
 
-# vim: se ts=3:
\ No newline at end of file
+# vim: se ts=3:
diff --git a/src/common/xmpp/auth_nb.py b/src/common/xmpp/auth_nb.py
index f53858a1adc2ea5861ac8e2a31340ea231deed27..64296a3f841fd0f01f0958b5de4bb6e07d9a54dc 100644
--- a/src/common/xmpp/auth_nb.py
+++ b/src/common/xmpp/auth_nb.py
@@ -20,7 +20,11 @@ Can be used both for client and transport authentication.
 from protocol import *
 from auth import *
 from client import PlugIn
-import sha,base64,random,dispatcher_nb
+import sha
+import base64
+import random
+import itertools
+import dispatcher_nb
 
 try:
 	import kerberos
@@ -143,27 +147,27 @@ class SASL(PlugIn):
 		self.MechanismHandler()
 
 	def MechanismHandler(self):
-		if "GSSAPI" in self.mecs and have_kerberos:
-			self.mecs.remove("GSSAPI")
-			rc, self.gss_vc = kerberos.authGSSClientInit('xmpp@' +
-				self._owner.socket._hostfqdn)
-			rc = kerberos.authGSSClientStep(self.gss_vc, '')
+		if 'GSSAPI' in self.mecs and have_kerberos:
+			self.mecs.remove('GSSAPI')
+			self.gss_vc = kerberos.authGSSClientInit('xmpp@' + \
+				self._owner.socket._hostfqdn)[1]
+			kerberos.authGSSClientStep(self.gss_vc, '')
 			response = kerberos.authGSSClientResponse(self.gss_vc)
 			node=Node('auth',attrs={'xmlns': NS_SASL, 'mechanism': 'GSSAPI'},
-                   payload=(response or ""))
-			self.mechanism = "GSSAPI"
+				payload=(response or ''))
+			self.mechanism = 'GSSAPI'
 			self.gss_step = GSS_STATE_STEP
-		elif "DIGEST-MD5" in self.mecs:
-			self.mecs.remove("DIGEST-MD5")
+		elif 'DIGEST-MD5' in self.mecs:
+			self.mecs.remove('DIGEST-MD5')
 			node=Node('auth',attrs={'xmlns': NS_SASL, 'mechanism': 'DIGEST-MD5'})
-			self.mechanism = "DIGEST-MD5"
-		elif "PLAIN" in self.mecs:
-			self.mecs.remove("PLAIN")
+			self.mechanism = 'DIGEST-MD5'
+		elif 'PLAIN' in self.mecs:
+			self.mecs.remove('PLAIN')
 			sasl_data='%s\x00%s\x00%s' % (self.username+'@' + self._owner.Server, 
 																	self.username, self.password)
 			node=Node('auth', attrs={'xmlns':NS_SASL,'mechanism':'PLAIN'}, 
 								payload=[base64.encodestring(sasl_data).replace('\n','')])
-			self.mechanism = "PLAIN"
+			self.mechanism = 'PLAIN'
 		else:
 			self.startsasl='failure'
 			self.DEBUG('I can only use DIGEST-MD5, GSSAPI and PLAIN mecanisms.', 'error')
@@ -234,10 +238,8 @@ class SASL(PlugIn):
 			else:
 				resp['realm'] = self._owner.Server
 			resp['nonce']=chal['nonce']
-			cnonce=''
-			for i in range(7):
-				cnonce += hex(int(random.random() * 65536 * 4096))[2:]
-			resp['cnonce'] = cnonce
+			resp['cnonce'] = ''.join("%x" % randint(0, 2**28) for randint in
+					itertools.repeat(random.randint, 7))
 			resp['nc'] = ('00000001')
 			resp['qop'] = 'auth'
 			resp['digest-uri'] = 'xmpp/'+self._owner.Server
@@ -288,7 +290,7 @@ class NonBlockingNonSASL(PlugIn):
 		self.DEBUG('Querying server about possible auth methods', 'start')
 		self.owner = owner 
 		
-		resp = owner.Dispatcher.SendAndWaitForResponse(
+		owner.Dispatcher.SendAndWaitForResponse(
 			Iq('get', NS_AUTH, payload=[Node('username', payload=[self.user])]), func=self._on_username
 		)
 		
@@ -312,9 +314,14 @@ class NonBlockingNonSASL(PlugIn):
 			token=query.getTagData('token')
 			seq=query.getTagData('sequence')
 			self.DEBUG("Performing zero-k authentication",'ok')
-			hash = sha.new(sha.new(self.password).hexdigest()+token).hexdigest()
-			for foo in xrange(int(seq)): 
-				hash = sha.new(hash).hexdigest()
+
+			def hasher(s):
+				return sha.new(s).hexdigest()
+
+			def hash_n_times(s, count):
+				return count and hasher(hash_n_times(s, count-1)) or s
+
+			hash = hash_n_times(hasher(hasher(self.password) + token), int(seq))
 			query.setTagData('hash',hash)
 			self._method='0k'
 		else:
@@ -386,7 +393,7 @@ class NonBlockingBind(Bind):
 			self._resource = []
 			
 		self._owner.onreceive(None)
-		resp=self._owner.Dispatcher.SendAndWaitForResponse(
+		self._owner.Dispatcher.SendAndWaitForResponse(
 			Protocol('iq',typ='set',
 				payload=[Node('bind', attrs={'xmlns':NS_BIND}, payload=self._resource)]), 
 				func=self._on_bound)
diff --git a/src/common/xmpp/browser.py b/src/common/xmpp/browser.py
index a23b6404f731b9a58c6a205fd26bf2a87ccd31e3..1b932bb1547048ef842ee506d1c065dc70d4b1c1 100644
--- a/src/common/xmpp/browser.py
+++ b/src/common/xmpp/browser.py
@@ -26,6 +26,8 @@ automatically called when user requests some node of your disco tree.
 from dispatcher import *
 from client import PlugIn
 
+DBG_BROWSER = "Browser"
+
 class Browser(PlugIn):
     """ WARNING! This class is for components only. It will not work in client mode!
 
@@ -80,7 +82,7 @@ class Browser(PlugIn):
     def __init__(self):
         """Initialises internal variables. Used internally."""
         PlugIn.__init__(self)
-        DBG_LINE='browser'
+        self.DBG_LINE = DBG_BROWSER
         self._exported_methods=[]
         self._handlers={'':{}}
 
@@ -89,6 +91,7 @@ class Browser(PlugIn):
             Used internally."""
         owner.RegisterHandler('iq',self._DiscoveryHandler,typ='get',ns=NS_DISCO_INFO)
         owner.RegisterHandler('iq',self._DiscoveryHandler,typ='get',ns=NS_DISCO_ITEMS)
+        owner.debug_flags.append(DBG_BROWSER)
 
     def plugout(self):
         """ Unregisters browser's iq handlers from your application dispatcher instance.
@@ -215,4 +218,4 @@ class Browser(PlugIn):
         conn.send(rep)
         raise NodeProcessed
 
-# vim: se ts=3:
\ No newline at end of file
+# vim: se ts=3:
diff --git a/src/common/xmpp/commands.py b/src/common/xmpp/commands.py
index ed4785e65267d3a0ec08244289a1f2a0860e5d53..37ffe9171ef294de9c999fe0815c45809d256d30 100644
--- a/src/common/xmpp/commands.py
+++ b/src/common/xmpp/commands.py
@@ -35,6 +35,8 @@ import math
 from protocol import *
 from client import PlugIn
 
+DBG_COMMANDS = 'commands'
+
 class Commands(PlugIn):
     """Commands is an ancestor of PlugIn and can be attached to any session.
     
@@ -47,7 +49,7 @@ class Commands(PlugIn):
     def __init__(self, browser):
         """Initialises class and sets up local variables"""
         PlugIn.__init__(self)
-        DBG_LINE='commands'
+        self.DBG_LINE = DBG_COMMANDS
         self._exported_methods=[]
         self._handlers={'':{}}
         self._browser = browser
@@ -59,13 +61,14 @@ class Commands(PlugIn):
         owner.RegisterHandler('iq',self._CommandHandler,typ='set',ns=NS_COMMANDS)
         owner.RegisterHandler('iq',self._CommandHandler,typ='get',ns=NS_COMMANDS)
         self._browser.setDiscoHandler(self._DiscoHandler,node=NS_COMMANDS,jid='')
+        owner.debug_flags.append(DBG_COMMANDS) 
         
     def plugout(self):
         """Removes handlers from the session"""
         # unPlug from the session and the disco manager
         self._owner.UnregisterHandler('iq',self._CommandHandler,ns=NS_COMMANDS)
         for jid in self._handlers:
-            self._browser.delDiscoHandler(self._DiscoHandler,node=NS_COMMANDS)
+            self._browser.delDiscoHandler(self._DiscoHandler,node=NS_COMMANDS,jid=jid)
         
     def _CommandHandler(self,conn,request):
         """The internal method to process the routing of command execution requests"""
@@ -194,7 +197,7 @@ class Command_Handler_Prototype(PlugIn):
     def __init__(self,jid=''):
         """Set up the class"""
         PlugIn.__init__(self)
-        DBG_LINE='command'
+        self.DBG_LINE='command'
         self.sessioncount = 0
         self.sessions = {}
         # Disco information for command list pre-formatted as a tuple
diff --git a/src/common/xmpp/dispatcher.py b/src/common/xmpp/dispatcher.py
index f88493ff1cbc856c0ccf6f53f867a54b82606fe9..84cd6f6d12cba25c12292f5488472187933ca7c0 100644
--- a/src/common/xmpp/dispatcher.py
+++ b/src/common/xmpp/dispatcher.py
@@ -28,12 +28,14 @@ from client import PlugIn
 DefaultTimeout=25
 ID=0
 
+DBG_DISPATCHER = 'dispatcher'
+
 class Dispatcher(PlugIn):
     """ Ancestor of PlugIn class. Handles XMPP stream, i.e. aware of stream headers.
         Can be plugged out/in to restart these headers (used for SASL f.e.). """
     def __init__(self):
         PlugIn.__init__(self)
-        DBG_LINE='dispatcher'
+        self.DBG_LINE = DBG_DISPATCHER
         self.handlers={}
         self._expected={}
         self._defaultHandler=None
@@ -82,6 +84,7 @@ class Dispatcher(PlugIn):
         self._owner.lastErr=None
         self._owner.lastErrCode=None
         self.StreamInit()
+        owner.debug_flags.append(DBG_DISPATCHER)
 
     def plugout(self):
         """ Prepares instance to be destructed. """
@@ -292,7 +295,6 @@ class Dispatcher(PlugIn):
         for key in list:
             if key: chain = chain + self.handlers[xmlns][name][key]
 
-        output=''
         if ID in session._expected:
             user=0
             if isinstance(session._expected[ID], tuple):
@@ -323,7 +325,6 @@ class Dispatcher(PlugIn):
             lastErrNode, lastErr and lastErrCode are set accordingly. """
         if timeout is None: timeout=DefaultTimeout
         self._expected[ID]=None
-        has_timed_out=0
         abort_time=time.time() + timeout
         self.DEBUG("Waiting for ID:%s with timeout %s..." % (ID,timeout),'wait')
         while not self._expected[ID]:
diff --git a/src/common/xmpp/dispatcher_nb.py b/src/common/xmpp/dispatcher_nb.py
index ee0eebdf61c2563b813241878e9e79fe7b8f52eb..604be9b02c32acd7c1bd542241c4756dbec1aba2 100644
--- a/src/common/xmpp/dispatcher_nb.py
+++ b/src/common/xmpp/dispatcher_nb.py
@@ -37,7 +37,7 @@ class Dispatcher(PlugIn):
 		Can be plugged out/in to restart these headers (used for SASL f.e.). '''
 	def __init__(self):
 		PlugIn.__init__(self)
-		DBG_LINE='dispatcher'
+		self.DBG_LINE='dispatcher'
 		self.handlers={}
 		self._expected={}
 		self._defaultHandler=None
@@ -338,7 +338,6 @@ class Dispatcher(PlugIn):
 		for key in list:
 			if key: chain = chain + self.handlers[xmlns][name][key]
 		
-		output=''
 		if ID in session._expected:
 			user=0
 			if isinstance(session._expected[ID], tuple):
diff --git a/src/common/xmpp/features_nb.py b/src/common/xmpp/features_nb.py
index 5326dee7cc71356eb4a8945c62f07b038108cc41..0895578ecb14c6bb922c23e5f1ad06249b71e6d5 100644
--- a/src/common/xmpp/features_nb.py
+++ b/src/common/xmpp/features_nb.py
@@ -118,7 +118,7 @@ def getRegInfo(disp, host, info={}, sync=True):
 		disp.SendAndCallForResponse(iq, _ReceivedRegInfo, {'agent': host })
 
 def _ReceivedRegInfo(con, resp, agent):
-	iq=Iq('get',NS_REGISTER,to=agent)
+	Iq('get',NS_REGISTER,to=agent)
 	if not isResultNode(resp):
 		error_msg = resp.getErrorMsg()
 		con.Event(NS_REGISTER,REGISTER_DATA_RECEIVED,(agent,None,False,error_msg))
diff --git a/src/common/xmpp/filetransfer.py b/src/common/xmpp/filetransfer.py
index 4ecae7ec8bedf889be33daab31497b9a700ed78d..6624a114376841ac6c4ba1f4b0693d827c9237a2 100644
--- a/src/common/xmpp/filetransfer.py
+++ b/src/common/xmpp/filetransfer.py
@@ -99,7 +99,8 @@ class IBB(PlugIn):
         self.DEBUG('SendHandler called','info')
         for sid in self._streams.keys():
             stream=self._streams[sid]
-            if stream['direction'][:2]=='|>': cont=1
+            if stream['direction'][:2]=='|>':
+                pass
             elif stream['direction'][0]=='>':
                 chunk=stream['fp'].read(stream['block-size'])
                 if chunk:
diff --git a/src/common/xmpp/transports.py b/src/common/xmpp/transports.py
index 86d1097cfcff16a5ae45050eb7d82732ebba46c3..f13f4612731522ca9cc291cc2eda4eb2b8651448 100644
--- a/src/common/xmpp/transports.py
+++ b/src/common/xmpp/transports.py
@@ -66,13 +66,15 @@ class error:
         """Serialise exception into pre-cached descriptive string."""
         return self._comment
 
+DBG_SOCKET = "socket"
+
 class TCPsocket(PlugIn):
     """ This class defines direct TCP connection method. """
     def __init__(self, server=None, use_srv=True):
         """ Cache connection point 'server'. 'server' is the tuple of (host, port)
             absolutely the same as standard tcp socket uses. """
         PlugIn.__init__(self)
-        self.DBG_LINE='socket'
+        self.DBG_LINE = DBG_SOCKET
         self._exported_methods=[self.send,self.disconnect]
 
         self._server = server
@@ -85,6 +87,7 @@ class TCPsocket(PlugIn):
         if not self.connect(self._server): return
         self._owner.Connection=self
         self._owner.RegisterDisconnectHandler(self.disconnected)
+        owner.debug_flags.append(DBG_SOCKET)
         return 'ok'
 
     def getHost(self):
@@ -235,7 +238,7 @@ class TLS(PlugIn):
         """
         if 'TLS' in owner.__dict__: return  # Already enabled.
         PlugIn.PlugIn(self,owner)
-        DBG_LINE='TLS'
+        self.DBG_LINE='TLS'
         if now: return self._startSSL()
         if self._owner.Dispatcher.Stream.features:
             try: self.FeaturesHandler(self._owner.Dispatcher,self._owner.Dispatcher.Stream.features)
diff --git a/src/common/xmpp/transports_nb.py b/src/common/xmpp/transports_nb.py
index 48166a4d62c5779b8feb4e5c78665ab407fe8a03..df456c11ece20313f9ee8b48dcb1cdc02e08c52c 100644
--- a/src/common/xmpp/transports_nb.py
+++ b/src/common/xmpp/transports_nb.py
@@ -38,6 +38,7 @@ import common.gajim
 
 USE_PYOPENSSL = False
 
+DBG_NONBLOCKINGTLS= 'NonBlockingTLS'
 try:
 	#raise ImportError("Manually disabled PyOpenSSL")
 	import OpenSSL.SSL
@@ -669,6 +670,8 @@ class NonBlockingTcp(PlugIn, IdleObject):
 		''' Return the 'port' value that is connection is [will be] made to.'''
 		return self._server[1]
 
+DBG_NONBLOCKINGTLS = "NonBlockingTLS"
+
 class NonBlockingTLS(PlugIn):
 	''' TLS connection used to encrypts already estabilished tcp connection.'''
 
@@ -687,12 +690,13 @@ class NonBlockingTLS(PlugIn):
 		if 'NonBlockingTLS' in owner.__dict__: 
 			return  # Already enabled.
 		PlugIn.PlugIn(self, owner)
-		DBG_LINE='NonBlockingTLS'
+		self.DBG_LINE = DBG_NONBLOCKINGTLS
+		owner.debug_flags.append(DBG_NONBLOCKINGTLS)
 		self.on_tls_start = on_tls_start
 		if now:
 			try:
 				res = self._startSSL()
-			except Exception, e:
+			except Exception:
 				log.error("PlugIn: while trying _startSSL():", exc_info=True)
 				#traceback.print_exc()
 				self._owner.socket.pollend()
@@ -867,7 +871,7 @@ class NonBlockingTLS(PlugIn):
 		self.DEBUG('Got starttls proceed response. Switching to TLS/SSL...','ok')
 		try:
 			self._startSSL()
-		except Exception, e:
+		except Exception:
 			log.error("StartTLSHandler:", exc_info=True)
 			#traceback.print_exc()
 			self._owner.socket.pollend()
@@ -1108,9 +1112,9 @@ class NBSOCKS5PROXYsocket(NonBlockingTcp):
 			return
 		# Get the bound address/port
 		elif reply[3] == "\x01":
-			begin, end = 3, 7
+			pass # begin, end = 3, 7
 		elif reply[3] == "\x03":
-			begin, end = 4, 4 + reply[4]
+			pass # begin, end = 4, 4 + reply[4]
 		else:
 			self.DEBUG('Invalid proxy reply', 'error')
 			self._owner.disconnected()
diff --git a/src/common/zeroconf/client_zeroconf.py b/src/common/zeroconf/client_zeroconf.py
index 47548dc739ca508b28b0b82e29e1ff0c49ed055e..166fd12dcb19389db78b9037107d86f2e5a35b8d 100644
--- a/src/common/zeroconf/client_zeroconf.py
+++ b/src/common/zeroconf/client_zeroconf.py
@@ -71,7 +71,7 @@ class ZeroconfListener(IdleObject):
 		# will fail when port is busy, or we don't have rights to bind
 		try:
 			self._serv.bind((ai[4][0], self.port))
-		except Exception, e:
+		except Exception:
 			# unable to bind, show error dialog
 			return None
 		self._serv.listen(socket.SOMAXCONN)
@@ -158,7 +158,7 @@ class P2PClient(IdleObject):
 		self.conn_holder.add_connection(self, self.Server, port, self.to)
 		# count messages in queue
 		for val in self.stanzaqueue:
-			stanza, is_message = val
+			is_message = val[1]
 			if is_message:
 				if self.fd == -1:
 					if on_not_ok:
diff --git a/src/common/zeroconf/connection_handlers_zeroconf.py b/src/common/zeroconf/connection_handlers_zeroconf.py
index 16da6722e82e5ace7098a27ba4bc9fe7aaf605ec..d9a4fb328658e089019166beae57873783f28f71 100644
--- a/src/common/zeroconf/connection_handlers_zeroconf.py
+++ b/src/common/zeroconf/connection_handlers_zeroconf.py
@@ -76,7 +76,6 @@ class ConnectionBytestream(connection_handlers.ConnectionBytestream):
 			receiver = file_props['receiver']
 		if sender is None:
 			sender = file_props['sender']
-		proxyhosts = []
 		sha_str = helpers.get_auth_sha(file_props['sid'], sender,
 			receiver)
 		file_props['sha_str'] = sha_str
@@ -382,6 +381,7 @@ class ConnectionHandlersZeroconf(ConnectionVcard, ConnectionBytestream, connecti
 		try:
 			idle.init()
 		except Exception:
+			global HAS_IDLE
 			HAS_IDLE = False
 
 	def _messageCB(self, ip, con, msg):
diff --git a/src/common/zeroconf/roster_zeroconf.py b/src/common/zeroconf/roster_zeroconf.py
index d70b8a1a2c9f6bd4d67dfa654f583e1f2562481d..b428c9b12824e2c13c5a5c4e291847bce821db2c 100644
--- a/src/common/zeroconf/roster_zeroconf.py
+++ b/src/common/zeroconf/roster_zeroconf.py
@@ -56,8 +56,8 @@ class Roster:
 		if not contact:
 			return
 
-		(service_jid, domain, interface, protocol, host, address, port, bare_jid, txt)  \
-			= contact
+		host, address, port = contact[4:7]
+		txt = contact[8]
 
 		self._data[jid]={}
 		self._data[jid]['ask'] = 'no'  #?
diff --git a/src/common/zeroconf/zeroconf_avahi.py b/src/common/zeroconf/zeroconf_avahi.py
index 4952c286dd3e1f53a2bdb050a9fd460378fd4f54..c0cfc9ab60d68ad98461d4e0d63ee59410dc349c 100644
--- a/src/common/zeroconf/zeroconf_avahi.py
+++ b/src/common/zeroconf/zeroconf_avahi.py
@@ -292,7 +292,7 @@ class Zeroconf:
 				return True
 			else:
 				return False
-		except dbus.DBusException, e:
+		except dbus.DBusException:
 			gajim.log.debug("Can't remove service. That should not happen")
 
 	def browse_domain(self, interface, protocol, domain):
@@ -429,4 +429,4 @@ class Zeroconf:
 
 # END Zeroconf
 
-# vim: se ts=3:
\ No newline at end of file
+# vim: se ts=3:
diff --git a/src/common/zeroconf/zeroconf_bonjour.py b/src/common/zeroconf/zeroconf_bonjour.py
index 80c985215140ad5579958317718f6aa8092ee77a..a57daf17358fa261630b72f4c2e57968aac57831 100644
--- a/src/common/zeroconf/zeroconf_bonjour.py
+++ b/src/common/zeroconf/zeroconf_bonjour.py
@@ -115,7 +115,9 @@ class Zeroconf:
 		}
 
 		# Split on '.' but do not split on '\.'
-		name, stype, protocol, domain, dummy = re.split('(?<!\\\\)\.', fullname)
+		result = re.split('(?<!\\\\)\.', fullname)
+		name = result[0]
+		protocol, domain = result[2:4]
 		
 		# Replace the escaped values
 		for src, trg in escaping.items():
@@ -329,7 +331,7 @@ class Zeroconf:
 
 		try:
 			pybonjour.DNSServiceUpdateRecord(self.service_sdRef, None, 0, self.txt)
-		except pybonjour.BonjourError, e:
+		except pybonjour.BonjourError:
 			return False
 		return True
 
diff --git a/src/config.py b/src/config.py
index 68baa884e8c0b523d193430ec2953c44fab9b685..6974f7816281b2286c7bcb7b4712874812d73d20 100644
--- a/src/config.py
+++ b/src/config.py
@@ -55,7 +55,7 @@ from common import helpers
 from common import gajim
 from common import connection
 from common import passwords
-from common import zeroconf
+from common.zeroconf import connection_zeroconf
 from common import dataforms
 from common import GnuPG
 
@@ -308,9 +308,6 @@ class PreferencesWindow:
 			self.xml.get_widget('sounds_scrolledwindow').set_sensitive(False)
 			self.xml.get_widget('browse_sounds_hbox').set_sensitive(False)
 
-		# sound player
-		player = gajim.config.get('soundplayer')
-
 		# sounds treeview
 		self.sound_tree = self.xml.get_widget('sounds_treeview')
 
@@ -612,27 +609,25 @@ class PreferencesWindow:
 		helpers.update_optional_features()
 
 	def apply_speller(self):
-		for acct in gajim.connections:
-			for ctrl in gajim.interface.msg_win_mgr.controls():
-				if isinstance(ctrl, chat_control.ChatControlBase):
-					try:
-						spell_obj = gtkspell.get_from_text_view(ctrl.msg_textview)
-					except Exception:
-						spell_obj = None
+		for ctrl in gajim.interface.msg_win_mgr.controls():
+			if isinstance(ctrl, chat_control.ChatControlBase):
+				try:
+					spell_obj = gtkspell.get_from_text_view(ctrl.msg_textview)
+				except Exception:
+					spell_obj = None
 
-					if not spell_obj:
-						gtkspell.Spell(ctrl.msg_textview)
+				if not spell_obj:
+					gtkspell.Spell(ctrl.msg_textview)
 
 	def remove_speller(self):
-		for acct in gajim.connections:
-			for ctrl in gajim.interface.msg_win_mgr.controls():
-				if isinstance(ctrl, chat_control.ChatControlBase):
-					try:
-						spell_obj = gtkspell.get_from_text_view(ctrl.msg_textview)
-					except Exception:
-						spell_obj = None
-					if spell_obj:
-						spell_obj.detach()
+		for ctrl in gajim.interface.msg_win_mgr.controls():
+			if isinstance(ctrl, chat_control.ChatControlBase):
+				try:
+					spell_obj = gtkspell.get_from_text_view(ctrl.msg_textview)
+				except Exception:
+					spell_obj = None
+				if spell_obj:
+					spell_obj.detach()
 
 	def on_speller_checkbutton_toggled(self, widget):
 		active = widget.get_active()
@@ -644,7 +639,7 @@ class PreferencesWindow:
 				lang = gajim.LANG
 			tv = gtk.TextView()
 			try:
-				spell = gtkspell.Spell(tv, lang)
+				gtkspell.Spell(tv, lang)
 			except:
 				dialogs.ErrorDialog(
 					_('Dictionary for lang %s not available') % lang,
@@ -1031,7 +1026,6 @@ class PreferencesWindow:
 			return
 		buf = self.xml.get_widget('msg_textview').get_buffer()
 		first_iter, end_iter = buf.get_bounds()
-		name = model.get_value(iter, 0)
 		model.set_value(iter, 1, buf.get_text(first_iter, end_iter))
 
 	def on_msg_treeview_key_press_event(self, widget, event):
@@ -1689,7 +1683,7 @@ class AccountsWindow:
 				gajim.interface.instances[account]['remove_account'] = \
 					RemoveAccountWindow(account)
 		if win_opened:
-			dialog = dialogs.ConfirmationDialog(
+			dialogs.ConfirmationDialog(
 				_('You have opened chat in account %s') % account,
 				_('All chat and groupchat windows will be closed. Do you want to '
 				'continue?'),
@@ -1894,7 +1888,7 @@ class AccountsWindow:
 
 	def on_synchronise_contacts_button1_clicked(self, widget):
 		try:
-			dialog = dialogs.SynchroniseSelectAccountDialog(self.current_account)
+			dialogs.SynchroniseSelectAccountDialog(self.current_account)
 		except GajimGeneralException:
 			# If we showed ErrorDialog, there will not be dialog instance
 			return
@@ -1908,7 +1902,7 @@ class AccountsWindow:
 					self.xml.get_widget('password_entry1').set_text(new_password)
 
 		try:
-			dialog = dialogs.ChangePasswordDialog(self.current_account, on_changed)
+			dialogs.ChangePasswordDialog(self.current_account, on_changed)
 		except GajimGeneralException:
 			# if we showed ErrorDialog, there will not be dialog instance
 			return
@@ -2073,14 +2067,10 @@ class AccountsWindow:
 				gajim.config.set_per('accounts', self.current_account, 'keyid',
 					keyID[0])
 
-		instance = dialogs.ChooseGPGKeyDialog(_('OpenPGP Key Selection'),
+		dialogs.ChooseGPGKeyDialog(_('OpenPGP Key Selection'),
 			_('Choose your OpenPGP key'), secret_keys, on_key_selected)
 
 	def on_use_gpg_agent_checkbutton_toggled(self, widget):
-		if self.current_account == gajim.ZEROCONF_ACC_NAME:
-			wiget_name_ext = '2'
-		else:
-			wiget_name_ext = '1'
 		self.on_checkbutton_toggled(widget, 'use_gpg_agent')
 
 	def on_edit_details_button1_clicked(self, widget):
@@ -2170,8 +2160,8 @@ class AccountsWindow:
 		elif not gajim.config.get('enable_zeroconf') and widget.get_active():
 			self.xml.get_widget('zeroconf_notebook').set_sensitive(True)
 			# enable (will create new account if not present)
-			gajim.connections[gajim.ZEROCONF_ACC_NAME] = common.zeroconf.\
-				connection_zeroconf.ConnectionZeroconf(gajim.ZEROCONF_ACC_NAME)
+			gajim.connections[gajim.ZEROCONF_ACC_NAME] = connection_zeroconf.\
+				ConnectionZeroconf(gajim.ZEROCONF_ACC_NAME)
 			if gajim.connections[gajim.ZEROCONF_ACC_NAME].gpg:
 				self.xml.get_widget('gpg_choose_button2').set_sensitive(True)
 			self.init_account_gpg()
@@ -2470,7 +2460,7 @@ class GroupchatConfigWindow:
 				return
 			model = self.affiliation_treeview[affiliation].get_model()
 			model.append((jid,'', '', ''))
-		instance = dialogs.InputDialog(title, prompt, ok_handler=on_ok)
+		dialogs.InputDialog(title, prompt, ok_handler=on_ok)
 
 	def on_remove_button_clicked(self, widget, affiliation):
 		selection = self.affiliation_treeview[affiliation].get_selection()
@@ -2576,7 +2566,7 @@ class RemoveAccountWindow:
 						gajim.connections[self.account].unregister_account(
 							self._on_remove_success)
 
-					w = dialogs.PassphraseDialog(
+					dialogs.PassphraseDialog(
 						_('Password Required'),
 						_('Enter your password for account %s') % self.account,
 						_('Save password'), ok_handler=on_ok)
@@ -2587,7 +2577,7 @@ class RemoveAccountWindow:
 				self._on_remove_success(True)
 
 		if gajim.connections[self.account].connected:
-			dialog = dialogs.ConfirmationDialog(
+			dialogs.ConfirmationDialog(
 				_('Account "%s" is connected to the server') % self.account,
 				_('If you remove it, the connection will be lost.'),
 				on_response_ok=remove)
diff --git a/src/conversation_textview.py b/src/conversation_textview.py
index 80751db47f344441980d1f8d58dcacc81b8fb244..7f0c445291e08e1b8a6579a263b0be0db2bd6e17 100644
--- a/src/conversation_textview.py
+++ b/src/conversation_textview.py
@@ -611,7 +611,7 @@ class ConversationTextview:
 	def on_textview_motion_notify_event(self, widget, event):
 		'''change the cursor to a hand when we are over a mail or an
 		url'''
-		pointer_x, pointer_y, spam = self.tv.window.get_pointer()
+		pointer_x, pointer_y = self.tv.window.get_pointer()[0:2]
 		x, y = self.tv.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT,
 			pointer_x, pointer_y)
 		tags = self.tv.get_iter_at_location(x, y).get_tags()
diff --git a/src/dataforms_widget.py b/src/dataforms_widget.py
index cddd0e583de630bb40a16637743fb63efeafebaa..0d45135433c0d001e1fbb9fedd5ea1d5e9b99119 100644
--- a/src/dataforms_widget.py
+++ b/src/dataforms_widget.py
@@ -567,7 +567,6 @@ class SingleForm(gtk.Table, object):
 
 	def on_jid_multi_remove_button_clicked(self, widget, treeview, field):
 		selection = treeview.get_selection()
-		model = treeview.get_model()
 		deleted = []
 
 		def remove(model, path, iter_, deleted):
diff --git a/src/dialogs.py b/src/dialogs.py
index 280a18bdd43102515da7a5e04eefc3779bf2ecb4..b2b1b11b44e1a5770149fe8c70e9957f1d21ce9f 100644
--- a/src/dialogs.py
+++ b/src/dialogs.py
@@ -436,7 +436,6 @@ class ChangeActivityDialog:
 		'''
 		Return activity and messsage (None if no activity selected)
 		'''
-		message = None
 		if self.checkbutton.get_active():
 			pep.user_send_activity(self.account, self.activity,
 				self.subactivity,
@@ -660,7 +659,7 @@ class ChangeStatusMessageDialog:
 					self.preset_messages_dict[msg_name] = msg_text
 					gajim.config.set_per('statusmsg', msg_name, 'message',
 						msg_text_1l)
-				dlg2 = ConfirmationDialog(_('Overwrite Status Message?'),
+				ConfirmationDialog(_('Overwrite Status Message?'),
 					_('This name is already used. Do you want to overwrite this '
 					'status message?'), on_response_ok=on_ok2)
 				return
@@ -1862,7 +1861,7 @@ class SynchroniseSelectAccountDialog:
 			return
 		else:
 			try:
-				dialog = SynchroniseSelectContactsDialog(self.account, remote_account)
+				SynchroniseSelectContactsDialog(self.account, remote_account)
 			except GajimGeneralException:
 				# if we showed ErrorDialog, there will not be dialog instance
 				return
@@ -2205,7 +2204,7 @@ class SingleMessageWindow:
 				if lang:
 					spell1.set_language(lang)
 					spell2.set_language(lang)
-			except gobject.GError, msg:
+			except gobject.GError:
 				AspellDictError(lang)
 
 		self.prepare_widgets_for(self.action)
@@ -2979,7 +2978,7 @@ class InvitationReceivedDialog:
 			except GajimGeneralException:
 				pass
 
-		dialog = YesNoDialog(pritext, sectext, on_response_yes=on_yes)
+		YesNoDialog(pritext, sectext, on_response_yes=on_yes)
 
 class ProgressDialog:
 	def __init__(self, title_text, during_text, messages_queue):
@@ -3166,7 +3165,6 @@ class AddSpecialNotificationDialog:
 		self.window.destroy()
 
 	def on_listen_sound_combobox_changed(self, widget):
-		model = widget.get_model()
 		active = widget.get_active()
 		if active == 1: # user selected 'choose sound'
 			def on_ok(widget, path_to_snd_file):
@@ -3669,9 +3667,6 @@ class TransformChatToMUC:
 		'server_and_guests_hseparator', 'server_select_label'):
 			self.__dict__[widget_to_add] = self.xml.get_widget(widget_to_add)
 
-		# set comboboxentry
-		renderer_servers = gtk.CellRendererText()
-
 		server_list = []
 		self.servers = gtk.ListStore(str)
 		self.server_list_comboboxentry.set_model(self.servers)
@@ -3914,7 +3909,7 @@ class GPGInfoWindow:
 				'encrypt messages.')
 			image = 'security-low-big.png'
 		else:
-			msgenc, error = gajim.connections[account].gpg.encrypt('test', [keyID])
+			error = gajim.connections[account].gpg.encrypt('test', [keyID])[1]
 			if error:
 				verification_status = _('''Contact's identity NOT verified''')
 				info = _('GPG key is assigned to this contact, but <b>you do not '
diff --git a/src/disco.py b/src/disco.py
index 12d999905308dd6261cec4bcc401d7f02d0e04f9..e09e63e531deccd0670284234307381a8ac63b82 100644
--- a/src/disco.py
+++ b/src/disco.py
@@ -971,7 +971,6 @@ _('This service does not contain any items to browse.'))
 
 	def _agent_info(self, jid, node, identities, features, data):
 		'''Callback for when we receive info about an agent's item.'''
-		addr = get_agent_address(jid, node)
 		iter = self._find_item(jid, node)
 		if not iter:
 			# Not in the treeview, stop
@@ -1101,7 +1100,7 @@ class ToplevelAgentBrowser(AgentBrowser):
 			if not props or self.tooltip.id != props[0]:
 				self.tooltip.hide_tooltip()
 		if props:
-			[row, col, x, y] = props
+			row = props[0]
 			iter = None
 			try:
 				iter = self.model.get_iter(row)
@@ -1432,7 +1431,7 @@ class ToplevelAgentBrowser(AgentBrowser):
 
 	def _find_category(self, cat, type_=None):
 		'''Looks up a category row and returns the iterator to it, or None.'''
-		cat, prio = self._friendly_category(cat, type_)
+		cat = self._friendly_category(cat, type_)[0]
 		iter = self.model.get_iter_root()
 		while iter:
 			if self.model.get_value(iter, 3).decode('utf-8') == cat:
@@ -1542,7 +1541,6 @@ class ToplevelAgentBrowser(AgentBrowser):
 		self._expand_all()
 
 	def _update_error(self, iter_, jid, node):
-		addr = get_agent_address(jid, node)
 		self.model[iter_][4] = 2
 		self._progress += 1
 		self._update_progressbar()
@@ -1637,7 +1635,6 @@ class MucBrowser(AgentBrowser):
 		room = model[iter][1].decode('utf-8')
 		if 'join_gc' not in gajim.interface.instances[self.account]:
 			try:
-				room_jid = '%s@%s' % (service, room)
 				dialogs.JoinGroupchatWindow(self.account, service)
 			except GajimGeneralException:
 				pass
diff --git a/src/features_window.py b/src/features_window.py
index 0665f4d63455d734c027327192d8d8d541ca1cd5..2b862b3ef9b504fd84bf6c84b9043623f47a4cc1 100644
--- a/src/features_window.py
+++ b/src/features_window.py
@@ -149,7 +149,6 @@ class FeaturesWindow:
 		if not rows:
 			return
 		path = rows[0]
-		available = self.model[path][1]
 		feature = self.model[path][0].decode('utf-8')
 		text = self.features[feature][1] + '\n'
 		if os.name == 'nt':
diff --git a/src/filetransfers_window.py b/src/filetransfers_window.py
index ab8368b576ef5641a9eaafb3ecb8391bc32c7691..f348f68b185af6ee0db91ec7b370073233d72a1c 100644
--- a/src/filetransfers_window.py
+++ b/src/filetransfers_window.py
@@ -160,7 +160,7 @@ class FileTransfersWindow:
 			dialog.destroy()
 			if 'file-name' not in file_props:
 				return
-			(path, file) = os.path.split(file_props['file-name'])
+			path = os.path.split(file_props['file-name'])[0]
 			if os.path.exists(path) and os.path.isdir(path):
 				helpers.launch_file_manager(path)
 			self.tree.get_selection().unselect_all()
@@ -286,7 +286,7 @@ _('Connection with peer cannot be established.'))
 				return
 			(jid, resource) = contact.split('/', 1)
 			contact = gajim.contacts.create_contact(jid=jid, resource=resource)
-		(file_dir, file_name) = os.path.split(file_path)
+		file_name = os.path.split(file_path)[1]
 		file_props = self.get_send_file_props(account, contact, 
 				file_path, file_name, file_desc)
 		if file_props is None:
@@ -317,7 +317,7 @@ _('Connection with peer cannot be established.'))
 		if 'desc' in file_props:
 			sec_text += '\n\t' + _('Description: %s') % file_props['desc']
 		prim_text = _('%s wants to send you a file:') % contact.jid
-		dialog, dialog2 = None, None
+		dialog = None
 
 		def on_response_ok(account, contact, file_props):
 
@@ -596,7 +596,7 @@ _('Connection with peer cannot be established.'))
 			text_labels += '<b>' + _('Recipient: ') + '</b>' 
 
 		if file_props['type'] == 'r':
-			(file_path, file_name) = os.path.split(file_props['file-name'])
+			file_name = os.path.split(file_props['file-name'])[1]
 		else:
 			file_name = file_props['name']
 		text_props = gobject.markup_escape_text(file_name) + '\n'
@@ -617,14 +617,13 @@ _('Connection with peer cannot be established.'))
 
 	def on_transfers_list_motion_notify_event(self, widget, event):
 		pointer = self.tree.get_pointer()
-		orig = widget.window.get_origin()
 		props = widget.get_path_at_pos(int(event.x), int(event.y))
 		self.height_diff = pointer[1] - int(event.y)
 		if self.tooltip.timeout > 0:
 			if not props or self.tooltip.id != props[0]:
 				self.tooltip.hide_tooltip()
 		if props:
-			[row, col, x, y] = props
+			row = props[0]
 			iter = None
 			try:
 				iter = self.model.get_iter(row)
@@ -886,7 +885,7 @@ _('Connection with peer cannot be established.'))
 		self.tooltip.hide_tooltip()
 		iter = None
 		try:
-			store, iter = self.tree.get_selection().get_selected()
+			iter = self.tree.get_selection().get_selected()[1]
 		except TypeError:
 			self.tree.get_selection().unselect_all()
 
@@ -904,8 +903,7 @@ _('Connection with peer cannot be established.'))
 		self.tooltip.hide_tooltip()
 		path = None
 		try:
-			path, column, x, y = self.tree.get_path_at_pos(int(event.x), 
-				int(event.y))
+			path = self.tree.get_path_at_pos(int(event.x), int(event.y))[0]
 		except TypeError:
 			self.tree.get_selection().unselect_all()
 		if path is None:
@@ -918,8 +916,7 @@ _('Connection with peer cannot be established.'))
 		self.tooltip.hide_tooltip()
 		path, iter = None, None
 		try:
-			path, column, x, y = self.tree.get_path_at_pos(int(event.x), 
-				int(event.y))
+			path = self.tree.get_path_at_pos(int(event.x), int(event.y))[0]
 		except TypeError:
 			self.tree.get_selection().unselect_all()
 		if event.button == 3: # Right click
@@ -939,7 +936,7 @@ _('Connection with peer cannot be established.'))
 		file_props = self.files_props[sid[0]][sid[1:]]
 		if 'file-name' not in file_props:
 			return
-		(path, file) = os.path.split(file_props['file-name'])
+		path = os.path.split(file_props['file-name'])[0]
 		if os.path.exists(path) and os.path.isdir(path):
 			helpers.launch_file_manager(path)
 
diff --git a/src/gajim.py b/src/gajim.py
index 3b9f002601389e9d5ffc51e1acbaf36c697e547d..a305136dd434db3fec0d15a171f2e79754864c9b 100755
--- a/src/gajim.py
+++ b/src/gajim.py
@@ -115,7 +115,7 @@ def parseOpts():
 	try:
 		shortargs = 'hqvl:p:c:'
 		longargs = 'help quiet verbose loglevel= profile= config_path='
-		opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs.split())
+		opts = getopt.getopt(sys.argv[1:], shortargs, longargs.split())[0]
 	except getopt.error, msg:
 		print msg
 		print 'for help use --help'
diff --git a/src/gajim_themes_window.py b/src/gajim_themes_window.py
index 46dc71e457932a16a6c0986020c223beb0c29a48..e5c7802b47bd67e68f636e7b876a65f4bbe6a41a 100644
--- a/src/gajim_themes_window.py
+++ b/src/gajim_themes_window.py
@@ -121,7 +121,7 @@ class GajimThemesWindow:
 		model.clear()
 		for config_theme in gajim.config.get_per('themes'):
 			theme = config_theme.replace('_', ' ')
-			iter = model.append([theme])
+			model.append([theme])
 
 	def select_active_theme(self):
 		model = self.themes_tree.get_model()
diff --git a/src/groupchat_control.py b/src/groupchat_control.py
index db8353c208cc0cbbbe8511492d45fa6f5aea1cf6..6217804f040e7e6f71d2f2fea5326aa51e0ff768 100644
--- a/src/groupchat_control.py
+++ b/src/groupchat_control.py
@@ -1008,7 +1008,6 @@ class GroupchatControl(ChatControlBase):
 		contact in a room'''
 		if nick is None:
 			nick = model[iter_][C_NICK].decode('utf-8')
-		fjid = gajim.construct_fjid(self.room_jid, nick) # 'fake' jid
 
 		ctrl = self._start_private_message(nick)
 		if ctrl and msg:
@@ -1809,7 +1808,7 @@ class GroupchatControl(ChatControlBase):
 			on_minimize(self)
 			return
 		if method == self.parent_win.CLOSE_ESC:
-			model, iter = self.list_treeview.get_selection().get_selected()
+			iter = self.list_treeview.get_selection().get_selected()[1]
 			if iter:
 				self.list_treeview.get_selection().unselect_all()
 				on_no(self)
@@ -1838,7 +1837,7 @@ class GroupchatControl(ChatControlBase):
 			sectext = _('If you close this window, you will be disconnected '
 					'from this group chat.')
 
-			dialog = dialogs.ConfirmationDialogCheck(pritext, sectext,
+			dialogs.ConfirmationDialogCheck(pritext, sectext,
 				_('Do _not ask me again'), on_response_ok=on_ok,
 				on_response_cancel=on_cancel)
 			return
@@ -1872,7 +1871,7 @@ class GroupchatControl(ChatControlBase):
 			# will work yet
 			gajim.connections[self.account].send_gc_subject(self.room_jid, subject)
 
-		instance = dialogs.InputTextDialog(_('Changing Subject'),
+		dialogs.InputTextDialog(_('Changing Subject'),
 			_('Please specify the new subject:'), input_str=self.subject,
 			ok_handler=on_ok)
 
@@ -1904,7 +1903,7 @@ class GroupchatControl(ChatControlBase):
 				jid)
 
 		# Ask for a reason
-		instance = dialogs.DubbleInputDialog(_('Destroying %s') % self.room_jid,
+		dialogs.DubbleInputDialog(_('Destroying %s') % self.room_jid,
 			_('You are going to definitively destroy this room.\n'
 			'You may specify a reason below:'),
 			_('You may also enter an alternate venue:'), ok_handler=on_ok)
@@ -1927,7 +1926,6 @@ class GroupchatControl(ChatControlBase):
 		path = treeview.get_selection().get_selected_rows()[1][0]
 		iter = model.get_iter(path)
 		type = model[iter][2]
-		account = model[iter][4].decode('utf-8')
 		if type != 'contact': # source is not a contact
 			return
 		contact_jid = data.decode('utf-8')
@@ -2055,7 +2053,7 @@ class GroupchatControl(ChatControlBase):
 	def on_list_treeview_key_press_event(self, widget, event):
 		if event.keyval == gtk.keysyms.Escape:
 			selection = widget.get_selection()
-			model, iter = selection.get_selected()
+			iter = selection.get_selected()[1]
 			if iter:
 				widget.get_selection().unselect_all()
 				return True
@@ -2079,7 +2077,7 @@ class GroupchatControl(ChatControlBase):
 				'none', reason)
 
 		# ask for reason
-		instance = dialogs.InputDialog(_('Kicking %s') % nick,
+		dialogs.InputDialog(_('Kicking %s') % nick,
 					_('You may specify a reason below:'), ok_handler=on_ok)
 
 	def mk_menu(self, event, iter_):
@@ -2235,13 +2233,13 @@ class GroupchatControl(ChatControlBase):
 		'''popup user's group's or agent menu'''
 		# hide tooltip, no matter the button is pressed
 		self.tooltip.hide_tooltip()
+		try:
+			pos = widget.get_path_at_pos(int(event.x), int(event.y))
+			path, x = pos[0], pos[2]
+		except TypeError:
+			widget.get_selection().unselect_all()
+			return
 		if event.button == 3: # right click
-			try:
-				path, column, x, y = widget.get_path_at_pos(int(event.x),
-					int(event.y))
-			except TypeError:
-				widget.get_selection().unselect_all()
-				return
 			widget.get_selection().select_path(path)
 			model = widget.get_model()
 			iter = model.get_iter(path)
@@ -2250,12 +2248,6 @@ class GroupchatControl(ChatControlBase):
 			return True
 
 		elif event.button == 2: # middle click
-			try:
-				path, column, x, y = widget.get_path_at_pos(int(event.x),
-					int(event.y))
-			except TypeError:
-				widget.get_selection().unselect_all()
-				return
 			widget.get_selection().select_path(path)
 			model = widget.get_model()
 			iter = model.get_iter(path)
@@ -2265,13 +2257,6 @@ class GroupchatControl(ChatControlBase):
 			return True
 
 		elif event.button == 1: # left click
-			try:
-				path, column, x, y = widget.get_path_at_pos(int(event.x),
-					int(event.y))
-			except TypeError:
-				widget.get_selection().unselect_all()
-				return
-
 			if gajim.single_click and not event.state & gtk.gdk.SHIFT_MASK:
 				self.on_row_activated(widget, path)
 				return True
@@ -2385,7 +2370,7 @@ class GroupchatControl(ChatControlBase):
 		# to ban we know the real jid. so jid is not fakejid
 		nick = gajim.get_nick_from_jid(jid)
 		# ask for reason
-		instance = dialogs.InputDialog(_('Banning %s') % nick,
+		dialogs.InputDialog(_('Banning %s') % nick,
 			_('You may specify a reason below:'), ok_handler=on_ok)
 
 	def grant_membership(self, widget, jid):
diff --git a/src/gtkexcepthook.py b/src/gtkexcepthook.py
index e75793251851bc5932a283997473eafed75f1db5..35400b551f15f9e0a0a27af8f1bd1035b1e8c050 100644
--- a/src/gtkexcepthook.py
+++ b/src/gtkexcepthook.py
@@ -82,7 +82,6 @@ def _info(type_, value, tb):
 	# on expand the details the dialog remains centered on screen
 	dialog.set_position(gtk.WIN_POS_CENTER_ALWAYS)
 
-	close_clicked = False
 	def on_dialog_response(dialog, response):
 		if response == RESPONSE_REPORT_BUG:
 			url = 'http://trac.gajim.org/wiki/HowToCreateATicket'
diff --git a/src/gtkgui_helpers.py b/src/gtkgui_helpers.py
index 69e9179be4a872ebb5218a5878f9995637faaa8d..f5979ff375f50907d94880b18f83ae6883116dfb 100644
--- a/src/gtkgui_helpers.py
+++ b/src/gtkgui_helpers.py
@@ -97,7 +97,7 @@ def popup_emoticons_under_button(menu, button, parent_win):
 		x = window_x + button_x
 		y = window_y + button_y
 
-		menu_width, menu_height = menu.size_request()
+		menu_height = menu.size_request()[1]
 
 		## should we pop down or up?
 		if (y + button.allocation.height + menu_height
@@ -494,7 +494,7 @@ def file_is_locked(path_to_file):
 			win32con.FILE_ATTRIBUTE_NORMAL,	# normal file
 			0								# no attr. template
 		)
-	except pywintypes.error, e:
+	except pywintypes.error:
 		return True
 	else: # in case all went ok, close file handle (go to hell WinAPI)
 		hfile.Close()
@@ -808,10 +808,6 @@ default_name = ''):
 			dialog.destroy()
 
 	def on_ok(widget):
-		def on_ok2(file_path, pixbuf):
-			pixbuf.save(file_path, 'jpeg')
-			dialog.destroy()
-
 		file_path = dialog.get_filename()
 		file_path = decode_filechooser_file_paths((file_path,))[0]
 		if os.path.exists(file_path):
diff --git a/src/history_manager.py b/src/history_manager.py
index 2dd20f5c6734526a9d28cc67a3240f5266c9d850..472f3173354b738fe1ec04f4f3de8035202cdf12 100755
--- a/src/history_manager.py
+++ b/src/history_manager.py
@@ -220,7 +220,7 @@ class HistoryManager:
 			def on_no():
 				gtk.main_quit()
 
-			dialog = dialogs.YesNoDialog(
+			dialogs.YesNoDialog(
 				_('Do you want to clean up the database? '
 				'(STRONGLY NOT RECOMMENDED IF GAJIM IS RUNNING)'),
 				_('Normally allocated database size will not be freed, '
@@ -296,7 +296,7 @@ class HistoryManager:
 		(user will see the first pm as if it was message in room's public chat)
 		and after that all okay'''
 		
-		possible_room_jid, possible_nick = jid.split('/', 1)
+		possible_room_jid = jid.split('/', 1)[0]
 		
 		self.cur.execute('SELECT jid_id FROM jids WHERE jid = ? AND type = ?',
 			(possible_room_jid, constants.JID_ROOM_TYPE))
@@ -421,9 +421,6 @@ class HistoryManager:
 			xml.get_widget('delete_menuitem').connect('activate',
 				self.on_delete_menuitem_activate, widget)
 			
-			liststore, list_of_paths = self.jids_listview.get_selection()\
-				.get_selected_rows()
-			
 			xml.signal_autoconnect(self)
 			xml.get_widget('context_menu').popup(None, None, None,
 				event.button, event.time)
diff --git a/src/history_window.py b/src/history_window.py
index ba345ad2282082e2aa3fa810e93ad25a8b2e1845..513e5b97285a0eb7ee9bcddf5e5e472a56d23406 100644
--- a/src/history_window.py
+++ b/src/history_window.py
@@ -333,7 +333,7 @@ class HistoryWindow:
 		# first day of month is 1 not 0
 		widget.clear_marks()
 		month = gtkgui_helpers.make_gtk_month_python_month(month)
-		weekday, days_in_this_month = calendar.monthrange(year, month)
+		days_in_this_month = calendar.monthrange(year, month)[1]
 		try:
 			log_days = gajim.logger.get_days_with_logs(self.jid, year, month,
 				days_in_this_month, self.account)
@@ -525,7 +525,7 @@ class HistoryWindow:
 		'''a row was double clicked, get date from row, and select it in calendar
 		which results to showing conversation logs for that date'''
 		# get currently selected date
-		cur_year, cur_month, cur_day = self.calendar.get_date()
+		cur_year, cur_month = self.calendar.get_date()[0:2]
 		cur_month = gtkgui_helpers.make_gtk_month_python_month(cur_month)
 		model = widget.get_model()
 		# make it a tupple (Y, M, D, 0, 0, 0...)
diff --git a/src/htmltextview.py b/src/htmltextview.py
index 7060396e00a5e96483d6266ca0e8d9a7193fe8ef..957ef3591a4aabd484ef4139fb48a360bfeeaab7 100644
--- a/src/htmltextview.py
+++ b/src/htmltextview.py
@@ -1034,7 +1034,7 @@ if __name__ == '__main__':
 	def on_textview_motion_notify_event(widget, event):
 		'''change the cursor to a hand when we are over a mail or an url'''
 		global change_cursor
-		pointer_x, pointer_y, spam = htmlview.window.get_pointer()
+		pointer_x, pointer_y = htmlview.window.get_pointer()[0:2]
 		x, y = htmlview.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, pointer_x,
 								   pointer_y)
 		tags = htmlview.get_iter_at_location(x, y).get_tags()
@@ -1043,7 +1043,6 @@ if __name__ == '__main__':
 					 gtk.gdk.Cursor(gtk.gdk.XTERM))
 			change_cursor = None
 		tag_table = htmlview.get_buffer().get_tag_table()
-		over_line = False
 		for tag in tags:
 			try:
 				if tag.is_anchor:
diff --git a/src/ipython_view.py b/src/ipython_view.py
index a58efcfef5cefaa1e70416a1967fed506fc50ada..cec10667da8313f1353c3d825169e36f9d697cd0 100644
--- a/src/ipython_view.py
+++ b/src/ipython_view.py
@@ -245,7 +245,6 @@ class IterableIPShell:
     @param header: Header to be printed before output
     @type header: string
     '''
-    stat = 0
     if verbose or debug: print header+cmd
     # flush stdout so we don't mangle python's buffering
     if not debug:
diff --git a/src/message_control.py b/src/message_control.py
index 26b6e84e12b7479cd56287251ec0db6658bc2bdb..b27a1e9a26e97c4d7dcd8443a9e26b6f5a5ce825 100644
--- a/src/message_control.py
+++ b/src/message_control.py
@@ -142,10 +142,8 @@ class MessageControl:
 
 		self.session = session
 
-		new_key = None
 		if session:
 			session.control = self
-			new_key = session.thread_id
 
 		if oldsession:
 			oldsession.control = None
diff --git a/src/message_window.py b/src/message_window.py
index 3a81efdb27bb9a9bb87285249f679257141a9556..2409f7aea9af26cd96730545416535cc46c862a3 100644
--- a/src/message_window.py
+++ b/src/message_window.py
@@ -213,7 +213,6 @@ class MessageWindow(object):
 			self.on_delete_ok -= 1
 
 		# Make sure all controls are okay with being deleted
-		ctrl_to_minimize = []
 		self.on_delete_ok = self.get_nb_controls()
 		for ctrl in self.controls():
 			ctrl.allow_shutdown(self.CLOSE_CLOSE_BUTTON, on_yes, on_no,
@@ -671,11 +670,7 @@ class MessageWindow(object):
 				yield ctrl
 
 	def get_nb_controls(self):
-		nb_ctrl = 0
-		for jid_dict in self._controls.values():
-			for ctrl in jid_dict.values():
-				nb_ctrl += 1
-		return nb_ctrl
+		return sum(len(jid_dict) for jid_dict in self._controls.values())
 
 	def move_to_next_unread_tab(self, forward):
 		ind = self.notebook.get_current_page()
@@ -776,7 +771,7 @@ class MessageWindow(object):
 		selection, type_, time):
 		'''Reorder the tabs according to the drop position'''
 		source_page_num = int(selection.data)
-		dest_page_num, to_right = self.get_tab_at_xy(x, y)
+		dest_page_num = self.get_tab_at_xy(x, y)[0]
 		source_child = self.notebook.get_nth_page(source_page_num)
 		if dest_page_num != source_page_num:
 			self.notebook.reorder_child(source_child, dest_page_num)
diff --git a/src/notify.py b/src/notify.py
index 05e3c3613065292bdd3b7dd8dc53d6234b8c03f2..05b0dc9b5133e23f29c3848582443f5ebfcbeb53 100644
--- a/src/notify.py
+++ b/src/notify.py
@@ -533,8 +533,8 @@ class DesktopNotification:
 			if gajim.interface.systray_enabled and \
 			gajim.config.get('attach_notifications_to_systray'):
 				x, y = gajim.interface.systray.img_tray.window.get_origin()
-				x_, y_, width, height, depth = \
-					gajim.interface.systray.img_tray.window.get_geometry()
+				width, height, = \
+					gajim.interface.systray.img_tray.window.get_geometry()[2:4]
 				pos_x = x + (width / 2)
 				pos_y = y + (height / 2)
 				hints = {'x': pos_x, 'y': pos_y}
diff --git a/src/roster_window.py b/src/roster_window.py
index 2d099a6178bc7b273199ae919011dbb4384ad553..6ef448acd4a3211ac18e1288893f3d6fecbcd1e6 100644
--- a/src/roster_window.py
+++ b/src/roster_window.py
@@ -514,7 +514,6 @@ class RosterWindow:
 		# Family might has changed (actual big brother not on top).
 		# Remove childs first then big brother
 		family_in_roster = False
-		big_brother_jid = None
 		for data in nearby_family:
 			_account = data['account']
 			_jid = data['jid']
@@ -821,7 +820,6 @@ class RosterWindow:
 
 	def remove_transport(self, jid, account):
 		'''Remove transport from roster and redraw account and group.'''
-		contact = gajim.contacts.get_contact_with_highest_priority(account, jid)
 		self.remove_contact(jid, account, force=True, backend=True)
 		return True
 
@@ -1144,8 +1142,8 @@ class RosterWindow:
 		is_big_brother = False
 		have_visible_children = False
 		if family:
-			nearby_family, bb_jid, bb_account = \
-				self._get_nearby_family_and_big_brother(family, account)
+			bb_jid, bb_account = \
+				self._get_nearby_family_and_big_brother(family, account)[1:]
 			is_big_brother = (jid, account) == (bb_jid, bb_account)
 			iters = self._get_contact_iter(jid, account)	
 			have_visible_children = iters \
@@ -1723,7 +1721,7 @@ class RosterWindow:
 			obj = bus.get_object('com.google.code.Awn', '/com/google/code/Awn')
 			awn = dbus.Interface(obj, 'com.google.code.Awn')
 			awn.SetTaskIconByName('Gajim', os.path.abspath(path))
-		except Exception, e:
+		except Exception:
 			pass
 
 	def music_track_changed(self, unused_listener, music_track_info,
@@ -1735,14 +1733,10 @@ class RosterWindow:
 			artist = ''
 			title = ''
 			source = ''
-			track = ''
-			length = ''
 		elif hasattr(music_track_info, 'paused') and music_track_info.paused == 0:
 			artist = ''
 			title = ''
 			source = ''
-			track = ''
-			length = ''
 		else:
 			artist = music_track_info.artist
 			title = music_track_info.title
@@ -1910,7 +1904,6 @@ class RosterWindow:
 				self.set_connecting_state(account)
 
 				if not gajim.connections[account].password:
-					passphrase = ''
 					text = _('Enter your password for account %s') % account
 					if passwords.USER_HAS_GNOMEKEYRING and \
 					not passwords.USER_USES_GNOMEKEYRING:
@@ -1924,7 +1917,7 @@ class RosterWindow:
 							passwords.save_password(account, passphrase)
 						keyid = gajim.config.get_per('accounts', account, 'keyid')
 						if keyid and not gajim.connections[account].gpg:
-							dialog = dialogs.WarningDialog(_('GPG is not usable'),
+							dialogs.WarningDialog(_('GPG is not usable'),
 								_('You will be connected to %s without OpenPGP.') % \
 								account)
 						self.send_status_continue(account, status, txt, auto, to)
@@ -1937,14 +1930,14 @@ class RosterWindow:
 							gajim.interface.systray.change_status('offline')
 						self.update_status_combobox()
 
-					w = dialogs.PassphraseDialog(_('Password Required'), text,
+					dialogs.PassphraseDialog(_('Password Required'), text,
 						_('Save password'), ok_handler=on_ok,
 						cancel_handler=on_cancel)
 					return
 
 				keyid = gajim.config.get_per('accounts', account, 'keyid')
 				if keyid and not gajim.connections[account].gpg:
-					dialog = dialogs.WarningDialog(_('GPG is not usable'),
+					dialogs.WarningDialog(_('GPG is not usable'),
 						_('You will be connected to %s without OpenPGP.') % account)
 
 		self.send_status_continue(account, status, txt, auto, to)
@@ -2278,7 +2271,7 @@ class RosterWindow:
 					break
 
 			if unread or recent:
-				dialog = dialogs.ConfirmationDialog(_('You have unread messages'),
+				dialogs.ConfirmationDialog(_('You have unread messages'),
 					_('Messages will only be available for reading them later if you'
 					' have history enabled and contact is in your roster.'),
 					on_response_ok=(on_continue2, message))
@@ -2386,7 +2379,7 @@ class RosterWindow:
 			if not props or self.tooltip.id != props[0]:
 				self.tooltip.hide_tooltip()
 		if props:
-			[row, col, x, y] = props
+			row = props[0]
 			titer = None
 			try:
 				titer = model.get_iter(row)
@@ -2540,7 +2533,6 @@ class RosterWindow:
 			if msg is None:
 				# user pressed Cancel to change status message dialog
 				return
-			model = self.modelfilter
 			accounts = []
 			if group is None:
 				for (contact, account) in list_:
@@ -2583,7 +2575,6 @@ class RosterWindow:
 
 	def on_unblock(self, widget, list_, group=None):
 		''' When clicked on the 'unblock' button in context menu. '''
-		model = self.modelfilter
 		accounts = []
 		if group is None:
 			for (contact, account) in list_:
@@ -2655,7 +2646,6 @@ class RosterWindow:
 		if 'rename' in gajim.interface.instances:
 			gajim.interface.instances['rename'].dialog.present()
 			return
-		model = self.modelfilter
 
 		# account is offline, don't allow to rename
 		if gajim.connections[account].connected < 2:
@@ -2768,7 +2758,7 @@ class RosterWindow:
 				u.keyID = helpers.prepare_and_validate_gpg_keyID(account,
 					contact.jid, keyID)
 
-		instance = dialogs.ChooseGPGKeyDialog(_('Assign OpenPGP Key'),
+		dialogs.ChooseGPGKeyDialog(_('Assign OpenPGP Key'),
 			_('Select a key to apply to the contact'), public_keys,
 			on_key_selected, selected=keyID)
 
@@ -2885,7 +2875,8 @@ class RosterWindow:
 		resource = None):
 		''' resource parameter MUST NOT be used if more than one contact in
 		list '''
-		for (contact, acct) in list_:
+		for e in list_:
+			contact = e[0]
 			contact_jid = contact.jid
 			if resource: # we MUST have one contact only in list_
 				contact_jid += '/' + resource
@@ -2930,10 +2921,10 @@ class RosterWindow:
 			helpers.launch_browser_mailer('url', url)
 
 	def on_change_activity_activate(self, widget, account):
-		dlg = dialogs.ChangeActivityDialog(account)
+		dialogs.ChangeActivityDialog(account)
 
 	def on_change_mood_activate(self, widget, account):
-		dlg = dialogs.ChangeMoodDialog(account)
+		dialogs.ChangeMoodDialog(account)
 
 	def on_change_status_message_activate(self, widget, account):
 		show = gajim.SHOW_LIST[gajim.connections[account].connected]
@@ -2992,8 +2983,7 @@ class RosterWindow:
 
 	def on_roster_treeview_button_release_event(self, widget, event):
 		try:
-			path, column, x, y = self.tree.get_path_at_pos(int(event.x),
-				int(event.y))
+			path = self.tree.get_path_at_pos(int(event.x), int(event.y))[0]
 		except TypeError:
 			return False
 
@@ -3009,8 +2999,8 @@ class RosterWindow:
 		# hide tooltip, no matter the button is pressed
 		self.tooltip.hide_tooltip()
 		try:
-			path, column, x, y = self.tree.get_path_at_pos(int(event.x),
-				int(event.y))
+			pos = self.tree.get_path_at_pos(int(event.x), int(event.y))
+			path, x = pos[0], pos[2]
 		except TypeError:
 			self.tree.get_selection().unselect_all()
 			return False
@@ -3121,7 +3111,6 @@ class RosterWindow:
 
 		if len(list_) == 1:
 			contact = list_[0][0]
-			account = list_[0][1]
 			pritext = _('Contact "%s" will be removed from your roster') % \
 				contact.get_shown_name()
 			if contact.sub == 'to':
@@ -3260,7 +3249,7 @@ class RosterWindow:
 				def on_cancel():
 					self.update_status_combobox()
 
-				dialog = dialogs.ConfirmationDialog(
+				dialogs.ConfirmationDialog(
 					_('You are participating in one or more group chats'),
 					_('Changing your status to invisible will result in '
 					'disconnection from those group chats. Are you sure you want to '
@@ -3414,7 +3403,7 @@ class RosterWindow:
 			gajim.interface.msg_win_mgr.one_window_opened():
 				# let message window close the tab
 				return
-			model, list_of_paths = self.tree.get_selection().get_selected_rows()
+			list_of_paths = self.tree.get_selection().get_selected_rows()[1]
 			if not len(list_of_paths) and gajim.interface.systray_enabled and \
 			not gajim.config.get('quit_on_roster_x_button'):
 				self.tooltip.hide_tooltip()
@@ -3533,8 +3522,8 @@ class RosterWindow:
 			jid = model[titer][C_JID].decode('utf-8')
 			account = model[titer][C_ACCOUNT].decode('utf-8')
 			family = gajim.contacts.get_metacontacts_family(account, jid)
-			nearby_family, bb_jid, bb_account = \
-				self._get_nearby_family_and_big_brother(family, account)
+			nearby_family = \
+				self._get_nearby_family_and_big_brother(family, account)[0]
 			# Redraw all brothers to show pending events
 			for data in nearby_family:
 				self.draw_contact(data['jid'], data['account'])
@@ -3573,8 +3562,8 @@ class RosterWindow:
 			jid = model[titer][C_JID].decode('utf-8')
 			account = model[titer][C_ACCOUNT].decode('utf-8')
 			family = gajim.contacts.get_metacontacts_family(account, jid)
-			nearby_family, bb_jid, bb_account = \
-				self._get_nearby_family_and_big_brother(family, account)
+			nearby_family  = \
+				self._get_nearby_family_and_big_brother(family, account)[0]
 			# Redraw all brothers to show pending events
 			for data in nearby_family:
 				self.draw_contact(data['jid'], data['account'])
@@ -3835,7 +3824,7 @@ class RosterWindow:
 	def drag_drop(self, treeview, context, x, y, timestamp):
 		target_list = treeview.drag_dest_get_target_list()
 		target = treeview.drag_dest_find_target(context, target_list)
-		selection = treeview.drag_get_data(context, target)
+		treeview.drag_get_data(context, target)
 		context.finish(False, True)
 		return True
 
@@ -5411,10 +5400,11 @@ class RosterWindow:
 			else:
 				execute_command_menuitem.set_sensitive(False)
 
-			our_jid_other_resource = None
-			if our_jid:
-				# It's another resource of us, be sure to send invite to her
-				our_jid_other_resource = contact.resource
+			# This does nothing:
+			# our_jid_other_resource = None
+			# if our_jid:
+			# 	# It's another resource of us, be sure to send invite to her
+			# 	our_jid_other_resource = contact.resource
 			# Else this var is useless but harmless in next connect calls
 
 			if gajim.capscache.is_supported(contact, NS_FILE):
@@ -5775,7 +5765,6 @@ class RosterWindow:
 	def make_groupchat_menu(self, event, titer):
 		model = self.modelfilter
 
-		path = model.get_path(titer)
 		jid = model[titer][C_JID].decode('utf-8')
 		account = model[titer][C_ACCOUNT].decode('utf-8')
 		contact = gajim.contacts.get_contact_with_highest_priority(account, jid)
@@ -6351,8 +6340,7 @@ class RosterWindow:
 		if not gajim.ZEROCONF_ACC_NAME in gajim.config.get_per('accounts'):
 			# Create zeroconf in config file
 			from common.zeroconf import connection_zeroconf
-			zeroconf = connection_zeroconf.ConnectionZeroconf(
-				gajim.ZEROCONF_ACC_NAME)
+			connection_zeroconf.ConnectionZeroconf(gajim.ZEROCONF_ACC_NAME)
 
 		if sys.platform == 'darwin':
 			self.setup_for_osx()
diff --git a/src/tooltips.py b/src/tooltips.py
index 13f371fb8b80daef85b8f394e703710e1a349279..4b00fba0b85f01d98102e22b3ec27a2068d5d224 100644
--- a/src/tooltips.py
+++ b/src/tooltips.py
@@ -655,7 +655,7 @@ class FileTransfersTooltip(BaseTooltip):
 		properties = []
 		name = file_props['name']
 		if file_props['type'] == 'r':
-			(file_path, file_name) = os.path.split(file_props['file-name'])
+			file_name = os.path.split(file_props['file-name'])[1]
 		else:
 			file_name = file_props['name']
 		properties.append((_('Name: '),