Coverage for /private/tmp/im/impacket/impacket/dcerpc/v5/enum.py : 52%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"""Python Enumerations"""
except NameError: def any(iterable): for element in iterable: if element: return True return False
"""Route attribute access on a class to __getattr__.
This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class's __getattr__ method; this is done by raising AttributeError.
"""
raise AttributeError()
raise AttributeError("can't set attribute")
raise AttributeError("can't delete attribute")
"""Returns True if obj is a descriptor, False otherwise.""" hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
"""Returns True if a __dunder__ name, False otherwise.""" name[2:3] != '_' and name[-3:-2] != '_' and len(name) > 4)
"""Returns True if a _sunder_ name, False otherwise.""" name[1:2] != '_' and name[-2:-1] != '_' and len(name) > 2)
"""Make the given class un-picklable.""" def _break_on_call_reduce(self): raise TypeError('%r cannot be pickled' % self) cls.__reduce__ = _break_on_call_reduce cls.__module__ = '<unknown>'
"""Track enum member order and ensure member names are not reused.
EnumMeta will use the names found in self._member_names as the enumeration member names.
"""
"""Changes anything not dundered or not a descriptor.
If a descriptor is added with the same name as an enum member, the name is removed from _member_names (this may leave a hole in the numerical sequence of values).
If an enum member name is used twice, an error is raised; duplicate values are not checked for.
Single underscore (sunder) names are reserved.
Note: in 3.x __order__ is simply discarded as a not necessary piece leftover from 2.x
""" return raise ValueError('_names_ are reserved for future Enum use') # descriptor overwriting an enum? raise TypeError('Attempted to reuse key: %r' % key) # enum overwriting a descriptor? raise TypeError('Key already defined as: %r' % self[key])
# Dummy value for Enum as EnumMeta explicitly checks for it, but of course until # EnumMeta finishes running the first time the Enum class doesn't exist. This # is also why there are checks in EnumMeta like `if Enum is not None`
"""Metaclass for Enum""" def __prepare__(metacls, cls, bases):
# an Enum class is final once enumeration items have been defined; it # cannot be mixed with other types (int, float, etc.) if it has an # inherited __new__ unless a new __new__ is defined (or the resulting # class will fail).
#if member_type is object: # use_args = False #else: # use_args = True first_enum) # save enum items into separate mapping so they don't get baked into # the new class
# py2 support for definition order order_specified = False else: else: del classdict['__order__'] order_specified = True if pyver < 3.0: __order__ = __order__.replace(',', ' ').split() aliases = [name for name in members if name not in __order__] __order__ += aliases
# check for illegal enum names (any others?) raise ValueError('Invalid enum member name(s): %s' % ( ', '.join(invalid_names), ))
# create our new Enum type
# Reverse value->name map for hashable values.
# check for a __getnewargs__, and if not present sabotage # pickling, since it won't work anyway member_type.__dict__.get('__getnewargs__') is None ): _make_class_unpicklable(enum_class)
# instantiate them, checking for duplicates as we go # we instantiate first instead of checking for duplicates first in case # a custom __new__ is doing something funky with the values -- such as # auto-numbering ;) __new__ = enum_class.__new__ else: args = value args = (args, ) # wrap it one more time else: enum_member = __new__(enum_class, *args) if not hasattr(enum_member, '_value_'): enum_member._value_ = member_type(*args) # If another member with the same value was already defined, the # new member becomes an alias to the existing one. else: # Aliases don't appear in member names (only in __members__). # This may fail if value is not hashable. We can't add the value # to the map, and by-value lookups for this value will be # linear. except TypeError: pass
# in Python2.x we cannot know definition order, so go with value order # unless __order__ was specified in the class definition enum_class._member_names_ = [ e[0] for e in sorted( [(name, enum_class._member_map_[name]) for name in enum_class._member_names_], key=lambda t: t[1]._value_ )]
# double check that repr and friends are not the mixin's or various # things break (such as pickle)
# method resolution and int's are not playing nice # Python's less than 2.6 use __cmp__
if issubclass(enum_class, int): setattr(enum_class, '__cmp__', getattr(int, '__cmp__'))
if issubclass(enum_class, int): for method in ( '__le__', '__lt__', '__gt__', '__ge__', '__eq__', '__ne__', '__hash__', ): setattr(enum_class, method, getattr(int, method))
# replace any other __new__ with our own (as long as Enum is not None, # anyway) -- again, this is to support pickle # if the user defined their own __new__, save it before it gets # clobbered in case they subclass later setattr(enum_class, '__member_new__', enum_class.__dict__['__new__'])
"""Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='red green blue')).
When used for the functional API: `module`, if set, will be stored in the new class' __module__ attribute; `type`, if set, will be mixed in as the first base class.
Note: if `module` is not set this routine will attempt to discover the calling module by walking the frame stack; if this is unsuccessful the resulting class will not be pickleable.
""" # otherwise, functional API: we're creating a new Enum type return cls._create_(value, names, module=module, type=type)
return isinstance(member, cls) and member.name in cls._member_map_
# nicer error message when someone tries to delete an attribute # (see issue19025). if attr in cls._member_map_: raise AttributeError( "%s: cannot delete Enum member." % cls.__name__) super(EnumMeta, cls).__delattr__(attr)
return (['__class__', '__doc__', '__members__', '__module__'] + self._member_names_)
def __members__(cls): """Returns a mapping of member name->value.
This mapping lists all enum members, including aliases. Note that this is a copy of the internal mapping.
"""
"""Return the enum member matching `name`
We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves.
""" except KeyError: raise AttributeError(name)
return (cls._member_map_[name] for name in cls._member_names_)
return (cls._member_map_[name] for name in reversed(cls._member_names_))
return len(cls._member_names_)
return "<enum %r>" % cls.__name__
"""Block attempts to reassign Enum members.
A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration.
""" raise AttributeError('Cannot reassign members.')
"""Convenience method to create a new Enum class.
`names` can be:
* A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member names. Values are auto-numbered from 1. * An iterable of (member name, value) pairs. * A mapping of member name -> value.
""" metacls = cls.__class__ if type is None: bases = (cls, ) else: bases = (type, cls) classdict = metacls.__prepare__(class_name, bases) __order__ = []
# special processing needed for names? if isinstance(names, str): names = names.replace(',', ' ').split() if isinstance(names, (tuple, list)) and isinstance(names[0], str): names = [(e, i+1) for (i, e) in enumerate(names)]
# Here, names is either an iterable of (name, value) or a mapping. for item in names: if isinstance(item, str): member_name, member_value = item, names[item] else: member_name, member_value = item classdict[member_name] = member_value __order__.append(member_name) # only set __order__ in classdict if name/value was not from a mapping if not isinstance(item, str): classdict['__order__'] = ' '.join(__order__) enum_class = metacls.__new__(metacls, class_name, bases, classdict)
# TODO: replace the frame hack if a blessed way to know the calling # module is ever developed if module is None: try: module = _sys._getframe(2).f_globals['__name__'] except (AttributeError, ValueError): pass if module is None: _make_class_unpicklable(enum_class) else: enum_class.__module__ = module
return enum_class
def _get_mixins_(bases): """Returns the type for creating enum members, and the first inherited enum class.
bases: the tuple of bases that was given to __new__
"""
# double check that we are not subclassing a class with existing # enumeration members; while we're at it, see if any other data # type has been mixed in so we can use the correct __new__ issubclass(base, Enum) and base._member_names_): raise TypeError("Cannot extend enumerations") # base is now the last base in bases raise TypeError("new enumerations must be created as " "`ClassName([mixin_type,] enum_type)`")
# get correct mix-in type (either mix-in type of Enum subclass, or # first base if last base is Enum) else: # most common: (IntEnum, int, Enum, object) # possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>, # <class 'int'>, <Enum 'Enum'>, # <class 'object'>) else:
@staticmethod def _find_new_(classdict, member_type, first_enum): """Returns the __new__ to be used for creating the enum members.
classdict: the class dictionary given to __new__ member_type: the data type whose __new__ will be used by default first_enum: enumeration to check for an overriding __new__
""" # now find the correct __new__, checking to see of one was defined # by the user; also check earlier enum classes in case a __new__ was # saved as __member_new__ __new__ = classdict.get('__new__', None) if __new__: return None, True, True # __new__, save_new, use_args
N__new__ = getattr(None, '__new__') O__new__ = getattr(object, '__new__') if Enum is None: E__new__ = N__new__ else: E__new__ = Enum.__dict__['__new__'] # check all possibles for __member_new__ before falling back to # __new__ for method in ('__member_new__', '__new__'): for possible in (member_type, first_enum): try: target = possible.__dict__[method] except (AttributeError, KeyError): target = getattr(possible, method, None) if target not in [ None, N__new__, O__new__, E__new__, ]: if method == '__member_new__': classdict['__new__'] = target return None, False, True if isinstance(target, staticmethod): target = target.__get__(member_type) __new__ = target break if __new__ is not None: break else: __new__ = object.__new__
# if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ if __new__ is object.__new__: use_args = False else: use_args = True
return __new__, False, use_args else: def _find_new_(classdict, member_type, first_enum): """Returns the __new__ to be used for creating the enum members.
classdict: the class dictionary given to __new__ member_type: the data type whose __new__ will be used by default first_enum: enumeration to check for an overriding __new__
""" # now find the correct __new__, checking to see of one was defined # by the user; also check earlier enum classes in case a __new__ was # saved as __member_new__
# should __new__ be saved as __member_new__ later?
# check all possibles for __member_new__ before falling back to # __new__ None, None.__new__, object.__new__, Enum.__new__, ): else:
# if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ else:
######################################################## # In order to support Python 2 and 3 with a single # codebase we have to create the Enum methods separately # and then use the `type(name, bases, dict)` method to # create the class. ########################################################
# all enum instances are actually created during class construction # without calling this method; this method is called by the metaclass' # __call__ (i.e. Color(3) ), and by pickle # For lookups like Color(Color.red) value = value.value #return value # by-value search for a matching enum member # see if it's in the reverse mapping (for hashable values) except TypeError: # not there, now do long search -- O(n) behavior for member in cls._member_map_.values(): if member.value == value: return member
return "<%s.%s: %r>" % ( self.__class__.__name__, self._name_, self._value_)
return "%s.%s" % (self.__class__.__name__, self._name_)
added_behavior = [m for m in self.__class__.__dict__ if m[0] != '_'] return (['__class__', '__doc__', '__module__', 'name', 'value'] + added_behavior)
# mixed-in Enums should use the mixed-in type's __format__, otherwise # we can get strange results with the Enum name showing up instead of # the value
# pure Enum branch if self._member_type_ is object: cls = str val = str(self) # mix-in branch else: cls = self._member_type_ val = self.value return cls.__format__(val, format_spec)
#################################### # Python's less than 2.6 use __cmp__
def __cmp__(self, other): if type(other) is self.__class__: if self is other: return 0 return -1 return NotImplemented raise TypeError("unorderable types: %s() and %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__cmp__'] = __cmp__ del __cmp__
else:
raise TypeError("unorderable types: %s() <= %s()" % (self.__class__.__name__, other.__class__.__name__))
raise TypeError("unorderable types: %s() < %s()" % (self.__class__.__name__, other.__class__.__name__))
raise TypeError("unorderable types: %s() >= %s()" % (self.__class__.__name__, other.__class__.__name__))
raise TypeError("unorderable types: %s() > %s()" % (self.__class__.__name__, other.__class__.__name__))
if type(other) is self.__class__: return self is other return NotImplemented
if type(other) is self.__class__: return self is not other return NotImplemented
return (self._value_, )
return hash(self._name_)
# _RouteClassAttributeToGetattr is used to provide access to the `name` # and `value` properties of enum members while keeping some measure of # protection from modification, while still allowing for an enumeration # to have members named `name` and `value`. This works because enumeration # members are not set directly on the enum class -- __getattr__ is # used to look them up.
def name(self):
def value(self):
# Enum has now been created ###########################
"""Enum where members are also (and must be) ints"""
"""Class decorator that ensures only unique members exist in an enumeration.""" duplicates = [] for name, member in enumeration.__members__.items(): if name != member.name: duplicates.append((name, member.name)) if duplicates: duplicate_names = ', '.join( ["%s -> %s" % (alias, name) for (alias, name) in duplicates] ) raise ValueError('duplicate names found in %r: %s' % (enumeration, duplicate_names) ) return enumeration |