Skip to content

Commit

Permalink
PEP8 cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
b-jazz committed Dec 23, 2014
1 parent 9e9568a commit ac1acb8
Show file tree
Hide file tree
Showing 14 changed files with 527 additions and 513 deletions.
22 changes: 12 additions & 10 deletions distribute_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,17 +140,17 @@ def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("distribute>="+version)
pkg_resources.require("distribute>=" + version)
return
except pkg_resources.VersionConflict:
e = sys.exc_info()[1]
if was_imported:
sys.stderr.write(
"The required version of distribute (>=%s) is not available,\n"
"and can't be installed while this script is running. Please\n"
"install a more recent version first, using\n"
"'easy_install -U distribute'."
"\n\n(Currently using %r)\n" % (version, e.args[0]))
"The required version of distribute (>=%s) is not available,\n"
"and can't be installed while this script is running. Please\n"
"install a more recent version first, using\n"
"'easy_install -U distribute'."
"\n\n(Currently using %r)\n" % (version, e.args[0]))
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
Expand All @@ -163,6 +163,7 @@ def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
if not no_fake:
_create_fake_setuptools_pkg_info(to_dir)


def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
Expand Down Expand Up @@ -275,6 +276,7 @@ def _after_install(dist):
placeholder = dist.get_command_obj('install').install_purelib
_create_fake_setuptools_pkg_info(placeholder)


def _create_fake_setuptools_pkg_info(placeholder):
if not placeholder or not os.path.exists(placeholder):
log.warn('Could not find the install location')
Expand Down Expand Up @@ -327,15 +329,15 @@ def _before_install():
def _under_prefix(location):
if 'install' not in sys.argv:
return True
args = sys.argv[sys.argv.index('install')+1:]
args = sys.argv[sys.argv.index('install') + 1:]
for index, arg in enumerate(args):
for option in ('--root', '--prefix'):
if arg.startswith('%s=' % option):
top_dir = arg.split('root=')[-1]
return location.startswith(top_dir)
elif arg == option:
if len(args) > index:
top_dir = args[index+1]
top_dir = args[index + 1]
return location.startswith(top_dir)
elif option == '--user' and USER_SITE is not None:
return location.startswith(USER_SITE)
Expand Down Expand Up @@ -382,7 +384,7 @@ def _fake_setuptools():
log.warn('Egg installation')
pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
if (os.path.exists(pkg_info) and
_same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
_same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
log.warn('Already patched.')
return
log.warn('Patching...')
Expand Down Expand Up @@ -421,7 +423,7 @@ def _extractall(self, path=".", members=None):
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 448 # decimal for oct 0700
tarinfo.mode = 448 # decimal for oct 0700
self.extract(tarinfo, path)

# Reverse sort directories.
Expand Down
48 changes: 24 additions & 24 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
news = open(news).read()
parts = re.split(r'([0-9\.]+)\s*\n\r?-+\n\r?', news)
found_news = ''
for i in range(len(parts)-1):
for i in range(len(parts) - 1):
if parts[i] == version:
found_news = parts[i+i]
found_news = parts[i + i]
break
if not found_news:
warnings.warn('No news for this version found.')
Expand All @@ -31,38 +31,38 @@

if found_news:
title = 'Changes in %s' % version
long_description += "\n%s\n%s\n" % (title, '-'*len(title))
long_description += '\n%s\n%s\n' % (title, '-' * len(title))
long_description += found_news

setup(
name = "stravalib",
version = version,
author = "Hans Lellelid",
author_email = "[email protected]",
url = "http://github.com/hozn/stravalib",
license = "Apache",
description = "Python library for interacting with Strava v3 REST API",
long_description = long_description,
packages = find_packages(),
name='stravalib',
version=version,
author='Hans Lellelid',
author_email='[email protected]',
url='http://github.com/hozn/stravalib',
license='Apache',
description='Python library for interacting with Strava v3 REST API',
long_description=long_description,
packages=find_packages(),
include_package_data=True,
package_data={'stravalib': ['tests/resources/*']},
install_requires=['python-dateutil{0}'.format('>=2.0,<3.0dev' if sys.version_info[0] == 3 else '>=1.5,<2.0dev'), # version 1.x is for python 2 and version 2.x is for python 3.
install_requires=['python-dateutil{0}'.format('>=2.0,<3.0dev' if sys.version_info[0] == 3 else '>=1.5,<2.0dev'), # version 1.x is for python 2 and version 2.x is for python 3.
'pytz',
'requests>=2.0,<3.0dev',
'beautifulsoup4>=4.0,<5.0dev',
'units'],
tests_require = ['nose>=1.0.3'],
test_suite = 'stravalib.tests',
tests_require=['nose>=1.0.3'],
test_suite='stravalib.tests',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
"Topic :: Software Development :: Libraries :: Python Modules",
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
use_2to3=True,
zip_safe=False # Technically it should be fine, but there are issues w/ 2to3
zip_safe=False # Technically it should be fine, but there are issues w/ 2to3
)
2 changes: 1 addition & 1 deletion stravalib/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from stravalib.client import Client
from stravalib.client import Client
67 changes: 38 additions & 29 deletions stravalib/attributes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""
Attribute types used for the model.
The types system provides a mechanism for serializing/un the data to/from JSON
structures and for capturing additional information about the model attributes.
The types system provides a mechanism for serializing/un the data to/from JSON
structures and for capturing additional information about the model attributes.
"""
import logging
from datetime import datetime, timedelta, tzinfo, date
Expand All @@ -12,25 +12,26 @@
import pytz
from units.quantity import Quantity

import stravalib.model
import stravalib.model

META = 1
SUMMARY = 2
DETAILED = 3


class Attribute(object):
"""
Base descriptor class for a Strava model attribute.
"""
_type = None

def __init__(self, type_, resource_states=None, units=None):
self.log = logging.getLogger('{0.__module__}.{0.__name__}'.format(self.__class__))
self.type = type_
self.resource_states = resource_states
self.data = WeakKeyDictionary()
self.units = units

def __get__(self, obj, clazz):
if obj is not None:
# It is being called on an object (not class)
Expand All @@ -43,34 +44,34 @@ def __get__(self, obj, clazz):
else:
# Rather than return the wrapped value, return the actual descriptor object
return self

def __set__(self, obj, val):
if val is not None:
self.data[obj] = self.unmarshal(val)
else:
self.data[obj] = None

@property
def type(self):
return self._type

@type.setter
def type(self, v):
self._type = v

def marshal(self, v):
"""
Turn this value into format for wire (JSON).
(By default this will just return the underlying object; subclasses
can override for specific behaviors -- e.g. date formatting.)
"""
return v

def unmarshal(self, v):
"""
Convert the value from parsed JSON structure to native python representation.
By default this will leave the value as-is since the JSON parsing routines
typically convert to native types. The exception may be date strings or other
more complex types, where subclasses will override this behavior.
Expand All @@ -83,12 +84,13 @@ def unmarshal(self, v):
v = self.type(v)
return v


class DateAttribute(Attribute):
"""
"""
def __init__(self, resource_states=None):
super(DateAttribute, self).__init__(date, resource_states=resource_states)

def unmarshal(self, v):
"""
Convert a date in "2012-12-13" format to a :class:`datetime.date` object.
Expand All @@ -97,14 +99,15 @@ def unmarshal(self, v):
# 2012-12-13
v = datetime.strptime(v, "%Y-%m-%d").date()
return v



class TimestampAttribute(Attribute):
"""
"""
def __init__(self, resource_states=None, tzinfo=pytz.utc):
super(TimestampAttribute, self).__init__(datetime, resource_states=resource_states)
self.tzinfo = tzinfo

def unmarshal(self, v):
"""
Convert a timestamp in "2012-12-13T03:43:19Z" format to a `datetime.datetime` object.
Expand All @@ -114,8 +117,10 @@ def unmarshal(self, v):
v = datetime.strptime(v, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=self.tzinfo)
return v


LatLon = namedtuple('LatLon', ['lat', 'lon'])


class LocationAttribute(Attribute):
"""
"""
Expand All @@ -128,7 +133,8 @@ def unmarshal(self, v):
if not isinstance(v, LatLon):
v = LatLon(lat=v[0], lon=v[1])
return v



class TimezoneAttribute(Attribute):
"""
"""
Expand All @@ -137,26 +143,27 @@ def __init__(self, resource_states=None):

def unmarshal(self, v):
"""
Convert a timestamp in format "(GMT-08:00) America/Los_Angeles" to
Convert a timestamp in format "(GMT-08:00) America/Los_Angeles" to
a `pytz.timestamp` object.
"""
if not isinstance(v, tzinfo):
# (GMT-08:00) America/Los_Angeles
tzname = v.split(' ')[-1]
v = pytz.timezone(tzname)
return v



class TimeIntervalAttribute(Attribute):
"""
Handles time durations, assumes upstream int value in seconds.
"""
def __init__(self, resource_states=None):
super(TimeIntervalAttribute, self).__init__(int, resource_states=resource_states)

def unmarshal(self, v):
"""
Convert the value from parsed JSON structure to native python representation.
By default this will leave the value as-is since the JSON parsing routines
typically convert to native types. The exception may be date strings or other
more complex types, where subclasses will override this behavior.
Expand All @@ -165,40 +172,41 @@ def unmarshal(self, v):
v = timedelta(seconds=v)
return v


class EntityAttribute(Attribute):
"""
Attribute for another entity.
"""
_lazytype = None

def __init__(self, *args, **kwargs):
super(EntityAttribute, self).__init__(*args, **kwargs)
self.bind_clients = WeakKeyDictionary()

@property
def type(self):
if self._lazytype:
clazz = getattr(stravalib.model, self._lazytype)
else:
clazz = self._type
return clazz

@type.setter
def type(self, v):
if isinstance(v, (str, bytes)):
# Supporting lazy class referencing
self._lazytype = v
else:
self._type = v

def __set__(self, obj, val):
if val is not None:
# If the "owning" object has a bind_client set, we want to pass that
# down into the objects we are deserializing here
self.data[obj] = self.unmarshal(val, bind_client=getattr(obj, 'bind_client'))
else:
self.data[obj] = None

def unmarshal(self, value, bind_client=None):
"""
Cast the specified value to the entity type.
Expand All @@ -208,19 +216,20 @@ def unmarshal(self, value, bind_client=None):
o = self.type()
if bind_client is not None and hasattr(o.__class__, 'bind_client'):
o.bind_client = bind_client

if isinstance(value, dict):
for (k,v) in value.items():
for (k, v) in value.items():
if not hasattr(o.__class__, k):
self.log.warning("Unable to set attribute {0} on entity {1!r}".format(k, o))
else:
#self.log.debug("Setting attribute {0} on entity {1!r}".format(k, o))
setattr(o, k, v)
setattr(o, k, v)
value = o
else:
raise Exception("Unable to unmarshall object {0!r}".format(value))
return value



class EntityCollection(EntityAttribute):

def unmarshal(self, values, bind_client=None):
Expand All @@ -233,4 +242,4 @@ def unmarshal(self, values, bind_client=None):
entity = super(EntityCollection, self).unmarshal(v, bind_client=bind_client)
#print "-------- Got entity: %r" % (entity,)
results.append(entity)
return results
return results
Loading

0 comments on commit ac1acb8

Please sign in to comment.