[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):
if type(ret) == types.ListType:
if isinstance(ret, list):
if ret[0] != 0:
raise Exception("Command failed: " + ret[1])
elif type(ret) == types.IntType:
elif isinstance(ret, int):
if ret != 0:
raise Exception("Command failed")
return

View File

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

View File

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

View File

@ -363,8 +363,7 @@ def get_uf_affiliation(affiliation):
return affiliation_name
def get_sorted_keys(adict):
keys = adict.keys()
keys.sort()
keys = sorted(adict.keys())
return keys
def to_one_line(msg):
@ -1072,8 +1071,7 @@ def get_notification_icon_tooltip_text():
def get_accounts_info():
'''helper for notification icon tooltip'''
accounts = []
accounts_list = gajim.contacts.get_accounts()
accounts_list.sort()
accounts_list = sorted(gajim.contacts.get_accounts())
for account in accounts_list:
status_idx = gajim.connections[account].connected
# 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:
S += form_type.getValue() + '<'
del fields['FORM_TYPE']
vars = fields.keys()
vars.sort()
vars = sorted(fields.keys())
for var in vars:
S += '%s<' % var
values = fields[var].getValues()
values.sort()
values = sorted(fields[var].getValues())
for value in values:
S += '%s<' % value

View File

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

View File

@ -195,14 +195,14 @@ class Browser(PlugIn):
q=rep.getTag('query')
if request.getQueryNS()==NS_DISCO_ITEMS:
# 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')
if lst is None:
conn.send(Error(request,ERR_ITEM_NOT_FOUND))
raise NodeProcessed
for item in lst: q.addChild('item',item)
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')
if dt is None:
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:
s = s + ' xmlns="%s"' % node.namespace
sorted_attrs = node.attrs.keys()
sorted_attrs.sort()
sorted_attrs = sorted(node.attrs.keys())
for key in sorted_attrs:
val = ustr(node.attrs[key])
# like XMLescape() but with whitespace and without &gt;

View File

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

View File

@ -170,7 +170,7 @@ class Debug:
self._remove_dupe_flags()
if log_file:
if type( log_file ) is type(''):
if isinstance(log_file, str):
try:
self._fh = open(log_file,'w')
except Exception:
@ -291,7 +291,7 @@ class Debug:
if not active_flags:
#no debuging at all
self.active = []
elif type( active_flags ) in ( types.TupleType, types.ListType ):
elif isinstance(active_flags, (tuple, list)):
flags = self._as_one_list( active_flags )
for t in flags:
if t not in self.debug_flags:
@ -333,7 +333,7 @@ class Debug:
return [ items ]
r = []
for l in items:
if type( l ) == type([]):
if isinstance(l, list):
lst2 = self._as_one_list( l )
for l2 in lst2:
self._append_unique_str(r, l2 )
@ -401,4 +401,4 @@ DBG_ALWAYS='always'
##Uncomment this to effectively disable all debugging and all debugging overhead.
#Debug=NoDebug
# vim: se ts=3:
# vim: se ts=3:

View File

@ -295,7 +295,7 @@ class Dispatcher(PlugIn):
output=''
if ID in session._expected:
user=0
if type(session._expected[ID])==type(()):
if isinstance(session._expected[ID], tuple):
cb,args=session._expected[ID]
session.DEBUG("Expected stanza arrived. Callback %s(%s) found!"%(cb,args),'ok')
try: cb(session,stanza,**args)
@ -382,4 +382,4 @@ class Dispatcher(PlugIn):
self._owner_send('</stream:stream>')
while self.Process(1): pass
# vim: se ts=3:
# vim: se ts=3:

View File

@ -337,7 +337,7 @@ class Dispatcher(PlugIn):
output=''
if ID in session._expected:
user=0
if type(session._expected[ID]) == type(()):
if isinstance(session._expected[ID], tuple):
cb,args = session._expected[ID]
session.DEBUG("Expected stanza arrived. Callback %s(%s) found!" % (cb, args), 'ok')
try:
@ -438,4 +438,4 @@ class Dispatcher(PlugIn):
''' Send a stream terminator. '''
self._owner.Connection.send('</stream:stream>')
# vim: se ts=3:
# vim: se ts=3:

View File

@ -254,7 +254,7 @@ class JID:
JID(node='node',domain='domain.org')
"""
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
else:
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 self['to']: self.setTo(self['to'])
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
for d in self.getTags('delay',namespace=NS_DELAY2):
try:
@ -732,7 +732,7 @@ class DataForm(Node):
if typ: self.setType(typ)
self.setNamespace(NS_DATA)
if title: self.setTitle(title)
if type(data)==type({}):
if isinstance(data, dict):
newdata=[]
for name in data.keys(): newdata.append(DataField(name,data[name]))
data=newdata

View File

@ -93,7 +93,7 @@ class Roster(PlugIn):
jid=self._owner.Server
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 type(self._data[jid.getStripped()]['resources'])!=type(dict()):
if not isinstance(self._data[jid.getStripped()]['resources'], dict):
self._data[jid.getStripped()]['resources']={}
item=self._data[jid.getStripped()]
typ=pres.getType()
@ -194,4 +194,4 @@ class Roster(PlugIn):
"""Returns the internal data representation of the roster."""
return self._data
# vim: se ts=3:
# vim: se ts=3:

View File

@ -141,7 +141,7 @@ class Session:
If you just want to shedule regular stanza for delivery use enqueue method.
"""
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)
def enqueue(self,stanza):
@ -349,4 +349,4 @@ class Session:
requires stream re-start so this state can have non-linear changes. """
if self._stream_state<newstate: self._stream_state=newstate
# vim: se ts=3:
# vim: se ts=3:

View File

@ -27,7 +27,7 @@ def XMLescape(txt):
ENCODING='utf-8'
def ustr(what):
"""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__()
except AttributeError: r=str(what)
if type(r)<>type(u''): return unicode(r,ENCODING)

View File

@ -138,8 +138,8 @@ class TCPsocket(PlugIn):
def send(self,raw_data):
""" Writes raw outgoing data. Blocks until done.
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')
elif type(raw_data)<>type(''): raw_data = ustr(raw_data).encode('utf-8')
if isinstance(raw_data, unicode): raw_data = raw_data.encode('utf-8')
elif type(raw_data)<>type(str): raw_data = ustr(raw_data).encode('utf-8')
try:
self._send(raw_data)
# Avoid printing messages that are empty keepalive packets.
@ -288,4 +288,4 @@ class TLS(PlugIn):
self._owner.Dispatcher.PlugOut()
dispatcher.Dispatcher().PlugIn(self._owner)
# vim: se ts=3:
# vim: se ts=3:

View File

@ -69,7 +69,7 @@ class ConnectionBytestream(connection_handlers.ConnectionBytestream):
def send_socks5_info(self, file_props, fast = True, receiver = None,
sender = None):
''' send iq for the present streamhosts and proxies '''
if type(self.peerhost) != tuple:
if not isinstance(self.peerhost, tuple):
return
port = gajim.config.get('file_transfers_port')
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'),
'in_and_out': _('Enter and leave only'),
'none': Q_('?print_status:None')}
opts = self.option_list.keys()
opts.sort()
opts = sorted(self.option_list.keys())
for opt in opts:
model.append([self.option_list[opt], opt])
@ -2892,8 +2891,7 @@ class ManageBookmarksWindow:
self.nick_entry.set_text('')
print_status = model[iter][7]
opts = self.option_list.keys()
opts.sort()
opts = sorted(self.option_list.keys())
self.print_status_combobox.set_active(opts.index(print_status))
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)
self.completion_dict = helpers.get_contact_dict_for_account(account)
# add all contacts to the model
keys = self.completion_dict.keys()
keys.sort()
keys = sorted(self.completion_dict.keys())
for jid in keys:
contact = self.completion_dict[jid]
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.close_button = self.xml.get_widget('close_button')
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])
self.to_entry.set_text(jid)
self.to_entry.set_sensitive(False)
@ -2209,8 +2208,7 @@ class SingleMessageWindow:
if to == '':
liststore = gtkgui_helpers.get_completion_liststore(self.to_entry)
self.completion_dict = helpers.get_contact_dict_for_account(account)
keys = self.completion_dict.keys()
keys.sort()
keys = sorted(self.completion_dict.keys())
for jid in keys:
contact = self.completion_dict[jid]
img = gajim.interface.jabber_state_images['16'][contact.show]

View File

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

View File

@ -2494,7 +2494,7 @@ class Interface:
for image in self.emoticons_images:
item = gtk.MenuItem()
img = gtk.Image()
if type(image[1]) == gtk.gdk.PixbufAnimation:
if isinstance(image[1], gtk.gdk.PixbufAnimation):
img.set_from_animation(image[1])
else:
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
or similar.
'''
if type(dims[0]) == float:
if isinstance(dims[0], float):
dims[0] = int(dims[0]*w)
elif not dims[0]:
dims[0] = w
if type(dims[1]) == float:
if isinstance(dims[1], float):
dims[1] = int(dims[1]*h)
if not dims[1]:
dims[1] = h

View File

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

View File

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

View File

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

View File

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

View File

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