Commit 196dd7e3 authored by Yann Leboulanger's avatar Yann Leboulanger
Browse files

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

parent 00543277
......@@ -70,10 +70,10 @@
###
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
......
......@@ -53,7 +53,7 @@ def _read_response(self, child_stdout):
# for that keyword.
resp = {}
while 1:
while True:
line = helpers.temp_failure_retry(child_stdout.readline)
if line == "": break
line = line.rstrip()
......
......@@ -153,7 +153,7 @@ def send_socks5_info(self, file_props, fast = True, receiver = None,
''' 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 @@ def send_vcard(self, vcard):
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:
......
......@@ -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
......
......@@ -214,8 +214,8 @@ def SASLHandler(self, conn, challenge):
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
......
......@@ -195,14 +195,14 @@ def _DiscoveryHandler(self,conn,request):
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))
......
......@@ -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;
......
......@@ -52,7 +52,7 @@ def __init__(self, server, port=5222, debug=['always', 'nodebuilder'], caller=No
# 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
......
......@@ -170,7 +170,7 @@ def __init__( self,
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 @@ def active_set( self, active_flags = None ):
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 @@ def _as_one_list( self, items ):
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 @@ def is_active( self, flag ):
##Uncomment this to effectively disable all debugging and all debugging overhead.
#Debug=NoDebug
# vim: se ts=3:
\ No newline at end of file
# vim: se ts=3:
......@@ -295,7 +295,7 @@ def dispatch(self,stanza,session=None,direct=0):
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 @@ def disconnect(self):
self._owner_send('</stream:stream>')
while self.Process(1): pass
# vim: se ts=3:
\ No newline at end of file
# vim: se ts=3:
......@@ -337,7 +337,7 @@ def dispatch(self, stanza, session=None, direct=0):
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 @@ def disconnect(self):
''' Send a stream terminator. '''
self._owner.Connection.send('</stream:stream>')
# vim: se ts=3:
\ No newline at end of file
# vim: se ts=3:
......@@ -254,7 +254,7 @@ def __init__(self, jid=None, node='', domain='', resource=''):
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 @@ def __init__(self, name=None, to=None, typ=None, frm=None, attrs={}, payload=[],
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 @@ def __init__(self, typ=None, data=[], title=None, node=None):
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
......
......@@ -93,7 +93,7 @@ def PresenceHandler(self,dis,pres):
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 @@ def getRaw(self):
"""Returns the internal data representation of the roster."""
return self._data
# vim: se ts=3:
\ No newline at end of file
# vim: se ts=3:
......@@ -141,7 +141,7 @@ def sendnow(self,chunk):
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 @@ def set_stream_state(self,newstate):
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:
\ No newline at end of file
# vim: se ts=3:
......@@ -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)
......
......@@ -138,8 +138,8 @@ def receive(self):
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 @@ def StartTLSHandler(self, conn, starttls):
self._owner.Dispatcher.PlugOut()
dispatcher.Dispatcher().PlugIn(self._owner)
# vim: se ts=3:
\ No newline at end of file
# vim: se ts=3:
......@@ -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')
......
......@@ -2689,8 +2689,7 @@ def __init__(self):
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 @@ def bookmark_selected(self, selection):
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):
......
......@@ -1940,8 +1940,7 @@ def __init__(self, account):
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 @@ def __init__(self, account, to='', action='', from_whom='', subject='',
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 @@ def __init__(self, account, to='', action='', from_whom='', subject='',
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]
......
......@@ -341,8 +341,7 @@ def print_result(self, res):
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 @@ def help_on_command(self, command):
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]:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment