[thorstenp] use isinstance rather than type(x) == y. use sorted()

This commit is contained in:
Yann Leboulanger 2008-10-11 09:59:52 +00:00
parent 00543277e4
commit 196dd7e30a
27 changed files with 52 additions and 68 deletions

View file

@ -70,10 +70,10 @@ exec ${TOPDIR}/MacOS/Python ${RESOURCEPATH}/gajim-remote.py $* \n\
### ###
def check(ret): def check(ret):
if type(ret) == types.ListType: if isinstance(ret, list):
if ret[0] != 0: if ret[0] != 0:
raise Exception("Command failed: " + ret[1]) raise Exception("Command failed: " + ret[1])
elif type(ret) == types.IntType: elif isinstance(ret, int):
if ret != 0: if ret != 0:
raise Exception("Command failed") raise Exception("Command failed")
return return

View file

@ -53,7 +53,7 @@ if gajim.HAVE_GPG:
# for that keyword. # for that keyword.
resp = {} resp = {}
while 1: while True:
line = helpers.temp_failure_retry(child_stdout.readline) line = helpers.temp_failure_retry(child_stdout.readline)
if line == "": break if line == "": break
line = line.rstrip() line = line.rstrip()

View file

@ -153,7 +153,7 @@ class ConnectionBytestream:
''' send iq for the present streamhosts and proxies ''' ''' send iq for the present streamhosts and proxies '''
if not self.connection or self.connected < 2: if not self.connection or self.connected < 2:
return return
if type(self.peerhost) != tuple: if not isinstance(self.peerhost, tuple):
return return
port = gajim.config.get('file_transfers_port') port = gajim.config.get('file_transfers_port')
ft_add_hosts_to_send = gajim.config.get('ft_add_hosts_to_send') ft_add_hosts_to_send = gajim.config.get('ft_add_hosts_to_send')
@ -998,7 +998,7 @@ class ConnectionVcard:
iq3 = iq2.addChild(i) iq3 = iq2.addChild(i)
for j in vcard[i]: for j in vcard[i]:
iq3.addChild(j).setData(vcard[i][j]) iq3.addChild(j).setData(vcard[i][j])
elif type(vcard[i]) == type([]): elif isinstance(vcard[i], list):
for j in vcard[i]: for j in vcard[i]:
iq3 = iq2.addChild(i) iq3 = iq2.addChild(i)
for k in j: for k in j:

View file

@ -363,8 +363,7 @@ def get_uf_affiliation(affiliation):
return affiliation_name return affiliation_name
def get_sorted_keys(adict): def get_sorted_keys(adict):
keys = adict.keys() keys = sorted(adict.keys())
keys.sort()
return keys return keys
def to_one_line(msg): def to_one_line(msg):
@ -1072,8 +1071,7 @@ def get_notification_icon_tooltip_text():
def get_accounts_info(): def get_accounts_info():
'''helper for notification icon tooltip''' '''helper for notification icon tooltip'''
accounts = [] accounts = []
accounts_list = gajim.contacts.get_accounts() accounts_list = sorted(gajim.contacts.get_accounts())
accounts_list.sort()
for account in accounts_list: for account in accounts_list:
status_idx = gajim.connections[account].connected status_idx = gajim.connections[account].connected
# uncomment the following to hide offline accounts # uncomment the following to hide offline accounts
@ -1238,12 +1236,10 @@ def compute_caps_hash(identities, features, dataforms=[], hash_method='sha-1'):
if form_type: if form_type:
S += form_type.getValue() + '<' S += form_type.getValue() + '<'
del fields['FORM_TYPE'] del fields['FORM_TYPE']
vars = fields.keys() vars = sorted(fields.keys())
vars.sort()
for var in vars: for var in vars:
S += '%s<' % var S += '%s<' % var
values = fields[var].getValues() values = sorted(fields[var].getValues())
values.sort()
for value in values: for value in values:
S += '%s<' % value S += '%s<' % value

View file

@ -214,8 +214,8 @@ class SASL(PlugIn):
chal = challenge_splitter(data) chal = challenge_splitter(data)
if not self.realm and 'realm' in chal: if not self.realm and 'realm' in chal:
self.realm = chal['realm'] self.realm = chal['realm']
if 'qop' in chal and ((type(chal['qop']) == str and \ if 'qop' in chal and ((isinstance(chal['qop'], str) and \
chal['qop'] =='auth') or (type(chal['qop']) == list and 'auth' in \ chal['qop'] =='auth') or (isinstance(chal['qop'], list) and 'auth' in \
chal['qop'])): chal['qop'])):
resp={} resp={}
resp['username'] = self.username resp['username'] = self.username

View file

@ -195,14 +195,14 @@ class Browser(PlugIn):
q=rep.getTag('query') q=rep.getTag('query')
if request.getQueryNS()==NS_DISCO_ITEMS: if request.getQueryNS()==NS_DISCO_ITEMS:
# handler must return list: [{jid,action,node,name}] # handler must return list: [{jid,action,node,name}]
if type(handler)==dict: lst=handler['items'] if isinstance(handler, dict): lst=handler['items']
else: lst=handler(conn,request,'items') else: lst=handler(conn,request,'items')
if lst is None: if lst is None:
conn.send(Error(request,ERR_ITEM_NOT_FOUND)) conn.send(Error(request,ERR_ITEM_NOT_FOUND))
raise NodeProcessed raise NodeProcessed
for item in lst: q.addChild('item',item) for item in lst: q.addChild('item',item)
elif request.getQueryNS()==NS_DISCO_INFO: elif request.getQueryNS()==NS_DISCO_INFO:
if type(handler)==dict: dt=handler['info'] if isinstance(handler, dict): dt=handler['info']
else: dt=handler(conn,request,'info') else: dt=handler(conn,request,'info')
if dt is None: if dt is None:
conn.send(Error(request,ERR_ITEM_NOT_FOUND)) conn.send(Error(request,ERR_ITEM_NOT_FOUND))

View file

@ -7,8 +7,7 @@ def c14n(node):
if not node.parent or node.parent.namespace != node.namespace: if not node.parent or node.parent.namespace != node.namespace:
s = s + ' xmlns="%s"' % node.namespace s = s + ' xmlns="%s"' % node.namespace
sorted_attrs = node.attrs.keys() sorted_attrs = sorted(node.attrs.keys())
sorted_attrs.sort()
for key in sorted_attrs: for key in sorted_attrs:
val = ustr(node.attrs[key]) val = ustr(node.attrs[key])
# like XMLescape() but with whitespace and without &gt; # like XMLescape() but with whitespace and without &gt;

View file

@ -52,7 +52,7 @@ class NBCommonClient(CommonClient):
# Who initiated this client # Who initiated this client
# Used to register the EventDispatcher # Used to register the EventDispatcher
self._caller = caller self._caller = caller
if debug and type(debug) != list: if debug and not isinstance(debug, list):
debug = ['always', 'nodebuilder'] debug = ['always', 'nodebuilder']
self._DEBUG = Debug.Debug(debug) self._DEBUG = Debug.Debug(debug)
self.DEBUG = self._DEBUG.Show self.DEBUG = self._DEBUG.Show

View file

@ -170,7 +170,7 @@ class Debug:
self._remove_dupe_flags() self._remove_dupe_flags()
if log_file: if log_file:
if type( log_file ) is type(''): if isinstance(log_file, str):
try: try:
self._fh = open(log_file,'w') self._fh = open(log_file,'w')
except Exception: except Exception:
@ -291,7 +291,7 @@ class Debug:
if not active_flags: if not active_flags:
#no debuging at all #no debuging at all
self.active = [] self.active = []
elif type( active_flags ) in ( types.TupleType, types.ListType ): elif isinstance(active_flags, (tuple, list)):
flags = self._as_one_list( active_flags ) flags = self._as_one_list( active_flags )
for t in flags: for t in flags:
if t not in self.debug_flags: if t not in self.debug_flags:
@ -333,7 +333,7 @@ class Debug:
return [ items ] return [ items ]
r = [] r = []
for l in items: for l in items:
if type( l ) == type([]): if isinstance(l, list):
lst2 = self._as_one_list( l ) lst2 = self._as_one_list( l )
for l2 in lst2: for l2 in lst2:
self._append_unique_str(r, l2 ) self._append_unique_str(r, l2 )

View file

@ -295,7 +295,7 @@ class Dispatcher(PlugIn):
output='' output=''
if ID in session._expected: if ID in session._expected:
user=0 user=0
if type(session._expected[ID])==type(()): if isinstance(session._expected[ID], tuple):
cb,args=session._expected[ID] cb,args=session._expected[ID]
session.DEBUG("Expected stanza arrived. Callback %s(%s) found!"%(cb,args),'ok') session.DEBUG("Expected stanza arrived. Callback %s(%s) found!"%(cb,args),'ok')
try: cb(session,stanza,**args) try: cb(session,stanza,**args)

View file

@ -337,7 +337,7 @@ class Dispatcher(PlugIn):
output='' output=''
if ID in session._expected: if ID in session._expected:
user=0 user=0
if type(session._expected[ID]) == type(()): if isinstance(session._expected[ID], tuple):
cb,args = session._expected[ID] cb,args = session._expected[ID]
session.DEBUG("Expected stanza arrived. Callback %s(%s) found!" % (cb, args), 'ok') session.DEBUG("Expected stanza arrived. Callback %s(%s) found!" % (cb, args), 'ok')
try: try:

View file

@ -254,7 +254,7 @@ class JID:
JID(node='node',domain='domain.org') JID(node='node',domain='domain.org')
""" """
if not jid and not domain: raise ValueError('JID must contain at least domain name') if not jid and not domain: raise ValueError('JID must contain at least domain name')
elif type(jid)==type(self): self.node,self.domain,self.resource=jid.node,jid.domain,jid.resource elif isinstance(jid, type(self)): self.node,self.domain,self.resource=jid.node,jid.domain,jid.resource
elif domain: self.node,self.domain,self.resource=node,domain,resource elif domain: self.node,self.domain,self.resource=node,domain,resource
else: else:
if jid.find('@')+1: self.node,jid=jid.split('@',1) if jid.find('@')+1: self.node,jid=jid.split('@',1)
@ -321,7 +321,7 @@ class Protocol(Node):
if not node and xmlns: self.setNamespace(xmlns) if not node and xmlns: self.setNamespace(xmlns)
if self['to']: self.setTo(self['to']) if self['to']: self.setTo(self['to'])
if self['from']: self.setFrom(self['from']) if self['from']: self.setFrom(self['from'])
if node and type(self)==type(node) and self.__class__==node.__class__ and 'id' in self.attrs: del self.attrs['id'] if node and isinstance(self, type(node)) and self.__class__==node.__class__ and 'id' in self.attrs: del self.attrs['id']
self.timestamp=None self.timestamp=None
for d in self.getTags('delay',namespace=NS_DELAY2): for d in self.getTags('delay',namespace=NS_DELAY2):
try: try:
@ -732,7 +732,7 @@ class DataForm(Node):
if typ: self.setType(typ) if typ: self.setType(typ)
self.setNamespace(NS_DATA) self.setNamespace(NS_DATA)
if title: self.setTitle(title) if title: self.setTitle(title)
if type(data)==type({}): if isinstance(data, dict):
newdata=[] newdata=[]
for name in data.keys(): newdata.append(DataField(name,data[name])) for name in data.keys(): newdata.append(DataField(name,data[name]))
data=newdata data=newdata

View file

@ -93,7 +93,7 @@ class Roster(PlugIn):
jid=self._owner.Server jid=self._owner.Server
jid=JID(jid) jid=JID(jid)
if jid.getStripped() not in self._data: self._data[jid.getStripped()]={'name':None,'ask':None,'subscription':'none','groups':['Not in roster'],'resources':{}} if jid.getStripped() not in self._data: self._data[jid.getStripped()]={'name':None,'ask':None,'subscription':'none','groups':['Not in roster'],'resources':{}}
if type(self._data[jid.getStripped()]['resources'])!=type(dict()): if not isinstance(self._data[jid.getStripped()]['resources'], dict):
self._data[jid.getStripped()]['resources']={} self._data[jid.getStripped()]['resources']={}
item=self._data[jid.getStripped()] item=self._data[jid.getStripped()]
typ=pres.getType() typ=pres.getType()

View file

@ -141,7 +141,7 @@ class Session:
If you just want to shedule regular stanza for delivery use enqueue method. If you just want to shedule regular stanza for delivery use enqueue method.
""" """
if isinstance(chunk,Node): chunk = chunk.__str__().encode('utf-8') if isinstance(chunk,Node): chunk = chunk.__str__().encode('utf-8')
elif type(chunk)==type(u''): chunk = chunk.encode('utf-8') elif isinstance(chunk, unicode): chunk = chunk.encode('utf-8')
self.enqueue(chunk) self.enqueue(chunk)
def enqueue(self,stanza): def enqueue(self,stanza):

View file

@ -27,7 +27,7 @@ def XMLescape(txt):
ENCODING='utf-8' ENCODING='utf-8'
def ustr(what): def ustr(what):
"""Converts object "what" to unicode string using it's own __str__ method if accessible or unicode method otherwise.""" """Converts object "what" to unicode string using it's own __str__ method if accessible or unicode method otherwise."""
if type(what) == type(u''): return what if isinstance(what, unicode): return what
try: r=what.__str__() try: r=what.__str__()
except AttributeError: r=str(what) except AttributeError: r=str(what)
if type(r)<>type(u''): return unicode(r,ENCODING) if type(r)<>type(u''): return unicode(r,ENCODING)

View file

@ -138,8 +138,8 @@ class TCPsocket(PlugIn):
def send(self,raw_data): def send(self,raw_data):
""" Writes raw outgoing data. Blocks until done. """ Writes raw outgoing data. Blocks until done.
If supplied data is unicode string, encodes it to utf-8 before send.""" If supplied data is unicode string, encodes it to utf-8 before send."""
if type(raw_data)==type(u''): raw_data = raw_data.encode('utf-8') if isinstance(raw_data, unicode): raw_data = raw_data.encode('utf-8')
elif type(raw_data)<>type(''): raw_data = ustr(raw_data).encode('utf-8') elif type(raw_data)<>type(str): raw_data = ustr(raw_data).encode('utf-8')
try: try:
self._send(raw_data) self._send(raw_data)
# Avoid printing messages that are empty keepalive packets. # Avoid printing messages that are empty keepalive packets.

View file

@ -69,7 +69,7 @@ class ConnectionBytestream(connection_handlers.ConnectionBytestream):
def send_socks5_info(self, file_props, fast = True, receiver = None, def send_socks5_info(self, file_props, fast = True, receiver = None,
sender = None): sender = None):
''' send iq for the present streamhosts and proxies ''' ''' send iq for the present streamhosts and proxies '''
if type(self.peerhost) != tuple: if not isinstance(self.peerhost, tuple):
return return
port = gajim.config.get('file_transfers_port') port = gajim.config.get('file_transfers_port')
ft_add_hosts_to_send = gajim.config.get('ft_add_hosts_to_send') ft_add_hosts_to_send = gajim.config.get('ft_add_hosts_to_send')

View file

@ -2689,8 +2689,7 @@ class ManageBookmarksWindow:
self.option_list = {'': _('Default'), 'all': Q_('?print_status:All'), self.option_list = {'': _('Default'), 'all': Q_('?print_status:All'),
'in_and_out': _('Enter and leave only'), 'in_and_out': _('Enter and leave only'),
'none': Q_('?print_status:None')} 'none': Q_('?print_status:None')}
opts = self.option_list.keys() opts = sorted(self.option_list.keys())
opts.sort()
for opt in opts: for opt in opts:
model.append([self.option_list[opt], opt]) model.append([self.option_list[opt], opt])
@ -2892,8 +2891,7 @@ class ManageBookmarksWindow:
self.nick_entry.set_text('') self.nick_entry.set_text('')
print_status = model[iter][7] print_status = model[iter][7]
opts = self.option_list.keys() opts = sorted(self.option_list.keys())
opts.sort()
self.print_status_combobox.set_active(opts.index(print_status)) self.print_status_combobox.set_active(opts.index(print_status))
def on_title_entry_changed(self, widget): def on_title_entry_changed(self, widget):

View file

@ -1940,8 +1940,7 @@ class NewChatDialog(InputDialog):
liststore = gtkgui_helpers.get_completion_liststore(self.input_entry) liststore = gtkgui_helpers.get_completion_liststore(self.input_entry)
self.completion_dict = helpers.get_contact_dict_for_account(account) self.completion_dict = helpers.get_contact_dict_for_account(account)
# add all contacts to the model # add all contacts to the model
keys = self.completion_dict.keys() keys = sorted(self.completion_dict.keys())
keys.sort()
for jid in keys: for jid in keys:
contact = self.completion_dict[jid] contact = self.completion_dict[jid]
img = gajim.interface.jabber_state_images['16'][contact.show] img = gajim.interface.jabber_state_images['16'][contact.show]
@ -2180,7 +2179,7 @@ class SingleMessageWindow:
self.cancel_button = self.xml.get_widget('cancel_button') self.cancel_button = self.xml.get_widget('cancel_button')
self.close_button = self.xml.get_widget('close_button') self.close_button = self.xml.get_widget('close_button')
self.message_tv_buffer.connect('changed', self.update_char_counter) self.message_tv_buffer.connect('changed', self.update_char_counter)
if type(to) == type([]): if isinstance(to, list):
jid = ', '.join( [i[0].jid + '/' + i[0].resource for i in to]) jid = ', '.join( [i[0].jid + '/' + i[0].resource for i in to])
self.to_entry.set_text(jid) self.to_entry.set_text(jid)
self.to_entry.set_sensitive(False) self.to_entry.set_sensitive(False)
@ -2209,8 +2208,7 @@ class SingleMessageWindow:
if to == '': if to == '':
liststore = gtkgui_helpers.get_completion_liststore(self.to_entry) liststore = gtkgui_helpers.get_completion_liststore(self.to_entry)
self.completion_dict = helpers.get_contact_dict_for_account(account) self.completion_dict = helpers.get_contact_dict_for_account(account)
keys = self.completion_dict.keys() keys = sorted(self.completion_dict.keys())
keys.sort()
for jid in keys: for jid in keys:
contact = self.completion_dict[jid] contact = self.completion_dict[jid]
img = gajim.interface.jabber_state_images['16'][contact.show] img = gajim.interface.jabber_state_images['16'][contact.show]

View file

@ -341,8 +341,7 @@ class GajimRemote:
for account_dict in res: for account_dict in res:
print self.print_info(0, account_dict, True) print self.print_info(0, account_dict, True)
elif self.command == 'prefs_list': elif self.command == 'prefs_list':
pref_keys = res.keys() pref_keys = sorted(res.keys())
pref_keys.sort()
for pref_key in pref_keys: for pref_key in pref_keys:
result = '%s = %s' % (pref_key, res[pref_key]) result = '%s = %s' % (pref_key, res[pref_key])
if isinstance(result, unicode): if isinstance(result, unicode):
@ -421,8 +420,7 @@ class GajimRemote:
def compose_help(self): def compose_help(self):
''' print usage, and list available commands ''' ''' print usage, and list available commands '''
str = _('Usage: %s command [arguments]\nCommand is one of:\n' ) % BASENAME str = _('Usage: %s command [arguments]\nCommand is one of:\n' ) % BASENAME
commands = self.commands.keys() commands = sorted(self.commands.keys())
commands.sort()
for command in commands: for command in commands:
str += ' ' + command str += ' ' + command
for argument in self.commands[command][1]: for argument in self.commands[command][1]:

View file

@ -2494,7 +2494,7 @@ class Interface:
for image in self.emoticons_images: for image in self.emoticons_images:
item = gtk.MenuItem() item = gtk.MenuItem()
img = gtk.Image() img = gtk.Image()
if type(image[1]) == gtk.gdk.PixbufAnimation: if isinstance(image[1], gtk.gdk.PixbufAnimation):
img.set_from_animation(image[1]) img.set_from_animation(image[1])
else: else:
img.set_from_pixbuf(image[1]) img.set_from_pixbuf(image[1])

View file

@ -641,11 +641,11 @@ class HtmlHandler(xml.sax.handler.ContentHandler):
pifbufs for every resize, gtk.gdk.Pixbuf.scale_simple pifbufs for every resize, gtk.gdk.Pixbuf.scale_simple
or similar. or similar.
''' '''
if type(dims[0]) == float: if isinstance(dims[0], float):
dims[0] = int(dims[0]*w) dims[0] = int(dims[0]*w)
elif not dims[0]: elif not dims[0]:
dims[0] = w dims[0] = w
if type(dims[1]) == float: if isinstance(dims[1], float):
dims[1] = int(dims[1]*h) dims[1] = int(dims[1]*h)
if not dims[1]: if not dims[1]:
dims[1] = h dims[1] = h

View file

@ -211,7 +211,7 @@ if __name__ == '__main__':
lfm = LastFM(argv[1]) lfm = LastFM(argv[1])
print lfm print lfm
while 1: while True:
if lfm.updateData(): if lfm.updateData():
print lfm.formatSongTitle() print lfm.formatSongTitle()
sleep(60) sleep(60)

View file

@ -2161,7 +2161,7 @@ class RosterWindow:
def close_all_from_dict(self, dic): def close_all_from_dict(self, dic):
'''close all the windows in the given dictionary''' '''close all the windows in the given dictionary'''
for w in dic.values(): for w in dic.values():
if type(w) == type({}): if isinstance(w, dict):
self.close_all_from_dict(w) self.close_all_from_dict(w)
else: else:
w.window.destroy() w.window.destroy()
@ -2824,7 +2824,7 @@ class RosterWindow:
contact = None): contact = None):
if contact is None: if contact is None:
dialogs.SingleMessageWindow(account, action='send') dialogs.SingleMessageWindow(account, action='send')
elif type(contact) == type([]): elif isinstance(contact, list):
dialogs.SingleMessageWindow(account, contact, 'send') dialogs.SingleMessageWindow(account, contact, 'send')
else: else:
jid = contact.jid jid = contact.jid
@ -4555,10 +4555,8 @@ class RosterWindow:
connected_accounts_with_private_storage = 0 connected_accounts_with_private_storage = 0
accounts_list = gajim.contacts.get_accounts()
accounts_list.sort()
# items that get shown whether an account is zeroconf or not # items that get shown whether an account is zeroconf or not
accounts_list = sorted(gajim.contacts.get_accounts())
if connected_accounts > 1: # 2 or more accounts? make submenus if connected_accounts > 1: # 2 or more accounts? make submenus
new_chat_sub_menu = gtk.Menu() new_chat_sub_menu = gtk.Menu()

View file

@ -234,8 +234,7 @@ class Systray:
account_menu_for_single_message) account_menu_for_single_message)
self.popup_menus.append(account_menu_for_single_message) self.popup_menus.append(account_menu_for_single_message)
accounts_list = gajim.contacts.get_accounts() accounts_list = sorted(gajim.contacts.get_accounts())
accounts_list.sort()
for account in accounts_list: for account in accounts_list:
if gajim.connections[account].is_zeroconf: if gajim.connections[account].is_zeroconf:
continue continue

View file

@ -460,8 +460,7 @@ class RosterTooltip(NotificationAreaTooltip):
iconset = 'dcraven' iconset = 'dcraven'
file_path = os.path.join(helpers.get_iconset_path(iconset), '16x16') file_path = os.path.join(helpers.get_iconset_path(iconset), '16x16')
contact_keys = contacts_dict.keys() contact_keys = sorted(contacts_dict.keys())
contact_keys.sort()
contact_keys.reverse() contact_keys.reverse()
for priority in contact_keys: for priority in contact_keys:
for contact in contacts_dict[priority]: for contact in contacts_dict[priority]:

View file

@ -228,8 +228,7 @@ class MockCall:
for p in self.params: for p in self.params:
s = s + sep + repr(p) s = s + sep + repr(p)
sep = ', ' sep = ', '
items = self.kwparams.items() items = sorted(self.kwparams.items())
items.sort()
for k,v in items: for k,v in items:
s = s + sep + k + '=' + repr(v) s = s + sep + k + '=' + repr(v)
sep = ', ' sep = ', '