Best Python code snippet using localstack_python
attributes.py
Source:attributes.py  
1"""2Attribute types used for the model.3The types system provides a mechanism for serializing/un the data to/from JSON4structures and for capturing additional information about the model attributes.5"""6from __future__ import division, absolute_import, print_function, unicode_literals7import logging8from datetime import datetime, timedelta, tzinfo, date9from collections import namedtuple10from weakref import WeakKeyDictionary, WeakValueDictionary11import arrow12import pytz13from units.quantity import Quantity14import six15import stravalib.model16# Depending on the type of request, objects will be returned in meta,  summary or detailed representations. The17# representation of the returned object is indicated by the resource_state attribute.18# (For more info, see https://strava.github.io/api/)19META = 120SUMMARY = 221DETAILED = 322class Attribute(object):23    """24    Base descriptor class for a Strava model attribute.25    """26    _type = None27    def __init__(self, type_, resource_states=None, units=None):28        self.log = logging.getLogger('{0.__module__}.{0.__name__}'.format(self.__class__))29        self.type = type_30        self.resource_states = resource_states31        self.data = WeakKeyDictionary()32        self.units = units33    def __get__(self, obj, clazz):34        if obj is not None:35            # It is being called on an object (not class)36            # This can cause infinite loops, when we're attempting to get the resource_state attribute ...37            #if hasattr(clazz, 'resource_state') \38            #   and obj.resource_state is not None \39            #   and not obj.resource_state in self.resource_states:40            #    raise AttributeError("attribute required resource state not satisfied by object")41            return self.data.get(obj)42        else:43            # Rather than return the wrapped value, return the actual descriptor object44            return self45    def __set__(self, obj, val):46        if val is not None:47            self.data[obj] = self.unmarshal(val)48        else:49            self.data[obj] = None50    @property51    def type(self):52        return self._type53    @type.setter54    def type(self, v):55        self._type = v56    def marshal(self, v):57        """58        Turn this value into format for wire (JSON).59        (By default this will just return the underlying object; subclasses60        can override for specific behaviors -- e.g. date formatting.)61        """62        return v63    def unmarshal(self, v):64        """65        Convert the value from parsed JSON structure to native python representation.66        By default this will leave the value as-is since the JSON parsing routines67        typically convert to native types. The exception may be date strings or other68        more complex types, where subclasses will override this behavior.69        """70        if self.units:71            # Note that we don't want to cast to type in this case!72            if not isinstance(v, Quantity):73                v = self.units(v)74        elif not isinstance(v, self.type):75            v = self.type(v)76        return v77class DateAttribute(Attribute):78    """79    """80    def __init__(self, resource_states=None):81        super(DateAttribute, self).__init__(date, resource_states=resource_states)82    def unmarshal(self, v):83        """84        Convert a date in "2012-12-13" format to a :class:`datetime.date` object.85        """86        if not isinstance(v, date):87            # 2012-12-1388            v = datetime.strptime(v, "%Y-%m-%d").date()89        return v90class TimestampAttribute(Attribute):91    """92    """93    def __init__(self, resource_states=None, tzinfo=pytz.utc):94        super(TimestampAttribute, self).__init__(datetime, resource_states=resource_states)95        self.tzinfo = tzinfo96    def unmarshal(self, v):97        """98        Convert a timestamp in "2012-12-13T03:43:19Z" format to a `datetime.datetime` object.99        """100        if not isinstance(v, datetime):101            if isinstance(v, six.integer_types):102                v = arrow.get(v)103            else:104                try:105                    # Most dates are in this format 2012-12-13T03:43:19Z106                    v = datetime.strptime(v, "%Y-%m-%dT%H:%M:%SZ")107                except ValueError:108                    # ... but not all.109                    v = arrow.get(v).datetime110            # Translate to specified TZ111            v = v.replace(tzinfo=self.tzinfo)112        return v113LatLon = namedtuple('LatLon', ['lat', 'lon'])114class LocationAttribute(Attribute):115    """116    """117    def __init__(self, resource_states=None):118        super(LocationAttribute, self).__init__(LatLon, resource_states=resource_states)119    def unmarshal(self, v):120        """121        """122        if not isinstance(v, LatLon):123            v = LatLon(lat=v[0], lon=v[1])124        return v125class TimezoneAttribute(Attribute):126    """127    """128    def __init__(self, resource_states=None):129        super(TimezoneAttribute, self).__init__(pytz.timezone, resource_states=resource_states)130    def unmarshal(self, v):131        """132        Convert a timestamp in format "(GMT-08:00) America/Los_Angeles" to133        a `pytz.timestamp` object.134        """135        if not isinstance(v, tzinfo):136            # (GMT-08:00) America/Los_Angeles137            tzname = v.split(' ', 1)[1]138            v = pytz.timezone(tzname)139        return v140class TimeIntervalAttribute(Attribute):141    """142    Handles time durations, assumes upstream int value in seconds.143    """144    def __init__(self, resource_states=None):145        super(TimeIntervalAttribute, self).__init__(int, resource_states=resource_states)146    def unmarshal(self, v):147        """148        Convert the value from parsed JSON structure to native python representation.149        By default this will leave the value as-is since the JSON parsing routines150        typically convert to native types. The exception may be date strings or other151        more complex types, where subclasses will override this behavior.152        """153        if not isinstance(v, timedelta):154            v = timedelta(seconds=v)155        return v156class ChoicesAttribute(Attribute):157    """158    Attribute where there are several choices the attribute may take.159    Allows conversion from the API value to a more helpful python value.160    """161    def __init__(self, *args, **kwargs):162        self.choices = kwargs.pop("choices", {})163        super(ChoicesAttribute, self).__init__(*args, **kwargs)164    def marshal(self, v):165        """166        Turn this value into API format.167        Do a reverse dictionary lookup on choices to find the original value. If168        there are no keys or too many keys for now we raise a NotImplementedError169        as marshal is not used anywhere currently. In the future we will want to170        fail gracefully.171        """172        orig = [i for i in self.choices if self.choices[i] == v]173        if len(orig) == 1:174            return orig[0]175        elif len(orig) == 0:176            # No such choice177            raise NotImplementedError("No such reverse choice {0} for field {1}.".format(v, self))178        else:179            # Too many choices. We could return one possible choice (e.g. orig[0]).180            raise NotImplementedError("Too many reverse choices {0} for value {1} for field {2}".format(orig, v, self))181    def unmarshal(self, v):182        """183        Convert the value from Strava API format to useful python representation.184        If the value does not appear in the choices attribute we log an error rather185        than raising an exception as this may be caused by a change to the API upstream186        so we want to fail gracefully.187        """188        try:189            return self.choices[v]190        except KeyError:191            self.log.warning("No such choice {0} for field {1}.".format(v, self))192            # Just return the value from the API193            return v194class EntityAttribute(Attribute):195    """196    Attribute for another entity.197    """198    _lazytype = None199    def __init__(self, *args, **kwargs):200        super(EntityAttribute, self).__init__(*args, **kwargs)201        self.bind_clients = WeakKeyDictionary()202    @property203    def type(self):204        if self._lazytype:205            clazz = getattr(stravalib.model, self._lazytype)206        else:207            clazz = self._type208        return clazz209    @type.setter210    def type(self, v):211        if isinstance(v, (six.text_type, six.binary_type)):212            # Supporting lazy class referencing213            self._lazytype = v214        else:215            self._type = v216    def __set__(self, obj, val):217        if val is not None:218            # If the "owning" object has a bind_client set, we want to pass that219            # down into the objects we are deserializing here220            self.data[obj] = self.unmarshal(val, bind_client=getattr(obj, 'bind_client', None))221        else:222            self.data[obj] = None223    def unmarshal(self, value, bind_client=None):224        """225        Cast the specified value to the entity type.226        """227        #self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value))228        if not isinstance(value, self.type):229            o = self.type()230            if bind_client is not None and hasattr(o.__class__, 'bind_client'):231                o.bind_client = bind_client232            if isinstance(value, dict):233                for (k, v) in value.items():234                    if not hasattr(o.__class__, k):235                        self.log.warning("Unable to set attribute {0} on entity {1!r}".format(k, o))236                    else:237                        #self.log.debug("Setting attribute {0} on entity {1!r}".format(k, o))238                        setattr(o, k, v)239                value = o240            else:241                raise Exception("Unable to unmarshall object {0!r}".format(value))242        return value243class EntityCollection(EntityAttribute):244    def unmarshal(self, values, bind_client=None):245        """246        Cast the list.247        """248        results = []249        for v in values:250            #print "-------- Processing value: %r" % (v,)251            entity = super(EntityCollection, self).unmarshal(v, bind_client=bind_client)252            #print "-------- Got entity: %r" % (entity,)253            results.append(entity)...attributes.pyi
Source:attributes.pyi  
1from typing import Any, NamedTuple2from weakref import WeakValueDictionary as WeakValueDictionary3META: int4SUMMARY: int5DETAILED: int6class Attribute:7    log: Any8    resource_states: Any9    data: Any10    units: Any11    def __init__(self, type_, resource_states: Any | None = ..., units: Any | None = ...) -> None: ...12    def __get__(self, obj, clazz): ...13    def __set__(self, obj, val) -> None: ...14    @property15    def type(self): ...16    @type.setter17    def type(self, v) -> None: ...18    def marshal(self, v): ...19    def unmarshal(self, v): ...20class DateAttribute(Attribute):21    def __init__(self, resource_states: Any | None = ...) -> None: ...22    def marshal(self, v): ...23    def unmarshal(self, v): ...24class TimestampAttribute(Attribute):25    tzinfo: Any26    def __init__(self, resource_states: Any | None = ..., tzinfo=...) -> None: ...27    def marshal(self, v): ...28    def unmarshal(self, v): ...29class LatLon(NamedTuple):30    lat: Any31    lon: Any32class LocationAttribute(Attribute):33    def __init__(self, resource_states: Any | None = ...) -> None: ...34    def marshal(self, v): ...35    def unmarshal(self, v): ...36class TimezoneAttribute(Attribute):37    def __init__(self, resource_states: Any | None = ...) -> None: ...38    def unmarshal(self, v): ...39    def marshal(self, v): ...40class TimeIntervalAttribute(Attribute):41    def __init__(self, resource_states: Any | None = ...) -> None: ...42    def unmarshal(self, v): ...43    def marshal(self, v): ...44class ChoicesAttribute(Attribute):45    choices: Any46    def __init__(self, *args, **kwargs) -> None: ...47    def marshal(self, v): ...48    def unmarshal(self, v): ...49class EntityAttribute(Attribute):50    bind_clients: Any51    def __init__(self, *args, **kwargs) -> None: ...52    @property53    def type(self): ...54    @type.setter55    def type(self, v) -> None: ...56    def __set__(self, obj, val) -> None: ...57    def marshal(self, v): ...58    def unmarshal(self, value, bind_client: Any | None = ...): ...59class EntityCollection(EntityAttribute):60    def marshal(self, values): ......Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
