Handling __str__ and __unicode__ in a Python2/3-agnostic manner.

This commit is contained in:
Adam Coddington 2013-10-11 18:25:47 -07:00
parent b3cc67c01f
commit af9f53eca6
4 changed files with 32 additions and 10 deletions

View file

@ -3,6 +3,7 @@ import uuid
import hashlib
import json
import requests
import sys
from pyicloud.exceptions import PyiCloudFailedLoginException
from pyicloud.services import (
@ -118,10 +119,14 @@ class PyiCloudService(object):
return CalendarService(service_root, self.session, self.params)
def __unicode__(self):
return u'iCloud API: %s' % self.user.get('apple_id')
return 'iCloud API: %s' % self.user.get('apple_id')
def __str__(self):
return unicode(self).encode('ascii', 'ignore')
as_unicode = self.__unicode__()
if sys.version_info[0] >= 3:
return as_unicode
else:
return as_unicode.encode('ascii', 'ignore')
def __repr__(self):
return '<%s>' % str(self)

View file

@ -1,4 +1,7 @@
import json
import sys
import six
from pyicloud.exceptions import PyiCloudNoDevicesException
@ -62,13 +65,17 @@ class FindMyiPhoneServiceManager(object):
return getattr(self._devices, attr)
def __unicode__(self):
return unicode(self._devices)
return six.text_type(self._devices)
def __str__(self):
return unicode(self).encode('ascii', 'ignore')
as_unicode = self.__unicode__()
if sys.version_info[0] >= 3:
return as_unicode
else:
return as_unicode.encode('ascii', 'ignore')
def __repr__(self):
return str(self)
return six.text_type(self)
class AppleDevice(object):
@ -169,13 +176,17 @@ class AppleDevice(object):
def __unicode__(self):
display_name = self['deviceDisplayName']
name = self['name']
return u'%s: %s' % (
return '%s: %s' % (
display_name,
name,
)
def __str__(self):
return unicode(self).encode('ascii', 'ignore')
as_unicode = self.__unicode__()
if sys.version_info[0] >= 3:
return as_unicode
else:
return as_unicode.encode('ascii', 'ignore')
def __repr__(self):
return '<AppleDevice(%s)>' % str(self)

View file

@ -1,4 +1,5 @@
from datetime import datetime
import sys
class UbiquityService(object):
@ -108,10 +109,14 @@ class UbiquityNode(object):
return self.name
def __str__(self):
return self.name.encode('unicode-escape')
as_unicode = self.__unicode__()
if sys.version_info[0] >= 3:
return as_unicode
else:
return as_unicode.encode('ascii', 'ignore')
def __repr__(self):
return "<%s: u'%s'>" % (
return "<%s: '%s'>" % (
self.type.capitalize(),
str(self)
self
)

View file

@ -1 +1,2 @@
requests>=1.2
six