Package pyxb :: Package binding :: Module datatypes
[hide private]
[frames] | no frames]

Source Code for Module pyxb.binding.datatypes

   1  # -*- coding: utf-8 -*- 
   2  # Copyright 2009-2013, Peter A. Bigot 
   3  # 
   4  # Licensed under the Apache License, Version 2.0 (the "License"); you may 
   5  # not use this file except in compliance with the License. You may obtain a 
   6  # copy of the License at: 
   7  # 
   8  #            http://www.apache.org/licenses/LICENSE-2.0 
   9  # 
  10  # Unless required by applicable law or agreed to in writing, software 
  11  # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
  12  # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
  13  # License for the specific language governing permissions and limitations 
  14  # under the License. 
  15   
  16  """Classes supporting U{XMLSchema Part 2: Datatypes<http://www.w3.org/TR/xmlschema-2/>}. 
  17   
  18  Each L{simple type definition<pyxb.xmlschema.structures.SimpleTypeDefinition>} component 
  19  instance is paired with at most one L{basis.simpleTypeDefinition} 
  20  class, which is a subclass of a Python type augmented with facets and 
  21  other constraining information.  This file contains the definitions of 
  22  these types. 
  23   
  24  We want the simple datatypes to be efficient Python values, but to 
  25  also hold specific constraints that don't apply to the Python types. 
  26  To do this, we subclass each PST.  Primitive PSTs inherit from the 
  27  Python type that represents them, and from a 
  28  pyxb.binding.basis.simpleTypeDefinition class which adds in the 
  29  constraint infrastructure.  Derived PSTs inherit from the parent PST. 
  30   
  31  There is an exception to this when the Python type best suited for a 
  32  derived SimpleTypeDefinition differs from the type associated with its 
  33  parent STD: for example, L{xsd:integer<integer>} has a value range 
  34  that requires it be represented by a Python C{long}, but 
  35  L{xsd:int<int>} allows representation by a Python C{int}.  In this 
  36  case, the derived PST class is structured like a primitive type, but 
  37  the PST associated with the STD superclass is recorded in a class 
  38  variable C{_XsdBaseType}. 
  39   
  40  Note the strict terminology: "datatype" refers to a class which is a 
  41  subclass of a Python type, while "type definition" refers to an 
  42  instance of either SimpleTypeDefinition or ComplexTypeDefinition. 
  43   
  44  """ 
  45   
  46  import logging 
  47  import re 
  48  import binascii 
  49  import base64 
  50  import decimal as python_decimal 
  51  from pyxb.exceptions_ import * 
  52  import pyxb.namespace 
  53  import pyxb.utils.unicode 
  54  from pyxb.utils import six 
  55  from . import basis 
  56   
  57  _log = logging.getLogger(__name__) 
  58   
  59  _PrimitiveDatatypes = [] 
  60  _DerivedDatatypes = [] 
  61  _ListDatatypes = [] 
62 63 # We use unicode as the Python type for anything that isn't a normal 64 # primitive type. Presumably, only enumeration and pattern facets 65 # will be applied. 66 -class anySimpleType (basis.simpleTypeDefinition, six.text_type):
67 """XMLSchema datatype U{anySimpleType<http://www.w3.org/TR/xmlschema-2/#dt-anySimpleType>}.""" 68 _XsdBaseType = None 69 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('anySimpleType') 70 71 @classmethod
72 - def XsdLiteral (cls, value):
73 return value
74 # anySimpleType is not treated as a primitive, because its variety
75 # must be absent (not atomic). 76 77 -class string (basis.simpleTypeDefinition, six.text_type):
78 """XMLSchema datatype U{string<http://www.w3.org/TR/xmlschema-2/#string>}.""" 79 _XsdBaseType = anySimpleType 80 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('string') 81 82 @classmethod
83 - def XsdLiteral (cls, value):
84 assert isinstance(value, cls) 85 return value
86 87 @classmethod
88 - def XsdValueLength (cls, value):
89 return len(value)
90 91 _PrimitiveDatatypes.append(string)
92 93 # It is illegal to subclass the bool type in Python, so we subclass 94 # int instead. 95 @six.unicode_convertible 96 -class boolean (basis.simpleTypeDefinition, six.int_type):
97 """XMLSchema datatype U{boolean<http://www.w3.org/TR/xmlschema-2/#boolean>}.""" 98 _XsdBaseType = anySimpleType 99 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('boolean') 100 101 @classmethod
102 - def XsdLiteral (cls, value):
103 if value: 104 return 'true' 105 return 'false'
106
107 - def __str__ (self):
108 if self: 109 return six.u('true') 110 return six.u('false')
111
112 - def __new__ (cls, *args, **kw):
113 args = cls._ConvertArguments(args, kw) 114 if 0 < len(args): 115 value = args[0] 116 args = args[1:] 117 if value in (1, 0, '1', '0', 'true', 'false'): 118 if value in (1, '1', 'true'): 119 iv = True 120 else: 121 iv = False 122 return super(boolean, cls).__new__(cls, iv, *args, **kw) 123 raise SimpleTypeValueError(cls, value) 124 return super(boolean, cls).__new__(cls, *args, **kw)
125 126 _PrimitiveDatatypes.append(boolean)
127 128 -class decimal (basis.simpleTypeDefinition, python_decimal.Decimal, basis._RepresentAsXsdLiteral_mixin):
129 """XMLSchema datatype U{decimal<http://www.w3.org/TR/xmlschema-2/#decimal>}. 130 131 This class uses Python's L{decimal.Decimal} class to support (by 132 default) 28 significant digits. Only normal and zero values are 133 valid; this means C{NaN} and C{Infinity} may be created during 134 calculations, but cannot be expressed in XML documents. 135 """ 136 _XsdBaseType = anySimpleType 137 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('decimal') 138
139 - def __new__ (cls, *args, **kw):
140 args = cls._ConvertArguments(args, kw) 141 # Pre Python 2.7 can't construct from float values 142 if (1 <= len(args)) and isinstance(args[0], six.float_type): 143 args = (str(args[0]),) + args[1:] 144 try: 145 rv = super(decimal, cls).__new__(cls, *args, **kw) 146 except python_decimal.DecimalException: 147 raise SimpleTypeValueError(cls, *args) 148 cls._CheckValidValue(rv) 149 return rv
150 151 @classmethod
152 - def _CheckValidValue (cls, value):
153 if not (value.is_normal() or value.is_zero()): 154 raise SimpleTypeValueError(cls, value) 155 return super(decimal, cls)._CheckValidValue(value)
156 157 @classmethod
158 - def XsdLiteral (cls, value):
159 (sign, digits, exponent) = value.normalize().as_tuple() 160 if (0 < len(digits)) and (0 == digits[0]): 161 digits = () 162 rchars = [] 163 if sign: 164 rchars.append('-') 165 digits_before = len(digits) + exponent 166 if 0 < digits_before: 167 rchars.extend(map(str, digits[:digits_before])) 168 digits = digits[digits_before:] 169 if (0 == len(digits)) and (0 < exponent): 170 rchars.extend(['0'] * exponent) 171 exponent = 0 172 else: 173 rchars.append('0') 174 rchars.append('.') 175 digits_after = -exponent 176 assert(0 <= digits_after) 177 if 0 < digits_after: 178 rchars.extend(['0'] * (digits_after - len(digits))) 179 rchars.extend(map(str, digits)) 180 else: 181 rchars.append('0') 182 return six.u('').join(rchars)
183 184 _PrimitiveDatatypes.append(decimal)
185 186 -class float (basis.simpleTypeDefinition, six.float_type):
187 """XMLSchema datatype U{float<http://www.w3.org/TR/xmlschema-2/#float>}.""" 188 _XsdBaseType = anySimpleType 189 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('float') 190 191 @classmethod
192 - def XsdLiteral (cls, value):
193 return '%s' % (value,)
194 195 _PrimitiveDatatypes.append(float)
196 197 -class double (basis.simpleTypeDefinition, six.float_type):
198 """XMLSchema datatype U{double<http://www.w3.org/TR/xmlschema-2/#double>}.""" 199 _XsdBaseType = anySimpleType 200 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('double') 201 202 @classmethod
203 - def XsdLiteral (cls, value):
204 return '%s' % (value,)
205 206 _PrimitiveDatatypes.append(double) 207 208 import datetime
209 210 -class duration (basis.simpleTypeDefinition, datetime.timedelta, basis._RepresentAsXsdLiteral_mixin):
211 """XMLSchema datatype U{duration<http://www.w3.org/TR/xmlschema-2/#duration>}. 212 213 This class uses the Python C{datetime.timedelta} class as its 214 underlying representation. This works fine as long as no months 215 or years are involved, and no negative durations are involved. 216 Because the XML Schema value space is so much larger, it is kept 217 distinct from the Python value space, which reduces to integral 218 days, seconds, and microseconds. 219 220 In other words, the implementation of this type is a little 221 shakey. 222 223 """ 224 225 _XsdBaseType = anySimpleType 226 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('duration') 227 228 __Lexical_re = re.compile('^(?P<neg>-?)P((?P<years>\d+)Y)?((?P<months>\d+)M)?((?P<days>\d+)D)?(?P<Time>T((?P<hours>\d+)H)?((?P<minutes>\d+)M)?(((?P<seconds>\d+)(?P<fracsec>\.\d+)?)S)?)?$') 229 230 # We do not use weeks 231 __XSDFields = ( 'years', 'months', 'days', 'hours', 'minutes', 'seconds' ) 232 __PythonFields = ( 'days', 'seconds', 'microseconds', 'minutes', 'hours' ) 233
234 - def negativeDuration (self):
235 return self.__negativeDuration
236 __negativeDuration = None 237
238 - def durationData (self):
239 return self.__durationData
240 __durationData = None 241
242 - def __new__ (cls, *args, **kw):
243 args = cls._ConvertArguments(args, kw) 244 have_kw_update = False 245 if not kw.get('_nil'): 246 if 0 == len(args): 247 raise SimpleTypeValueError(cls, args) 248 text = args[0] 249 if kw.get('_nil'): 250 data = dict(zip(cls.__PythonFields, len(cls.__PythonFields) * [0,])) 251 negative_duration = False 252 elif isinstance(text, six.string_types): 253 match = cls.__Lexical_re.match(text) 254 if match is None: 255 raise SimpleTypeValueError(cls, text) 256 match_map = match.groupdict() 257 if 'T' == match_map.get('Time'): 258 # Can't have T without additional time information 259 raise SimpleTypeValueError(cls, text) 260 261 negative_duration = ('-' == match_map.get('neg')) 262 263 fractional_seconds = 0.0 264 if match_map.get('fracsec') is not None: 265 fractional_seconds = six.float_type('0%s' % (match_map['fracsec'],)) 266 usec = six.int_type(1000000 * fractional_seconds) 267 if negative_duration: 268 kw['microseconds'] = - usec 269 else: 270 kw['microseconds'] = usec 271 else: 272 # Discard any bogosity passed in by the caller 273 kw.pop('microsecond', None) 274 275 data = { } 276 for fn in cls.__XSDFields: 277 v = match_map.get(fn, 0) 278 if v is None: 279 v = 0 280 data[fn] = six.int_type(v) 281 if fn in cls.__PythonFields: 282 if negative_duration: 283 kw[fn] = - data[fn] 284 else: 285 kw[fn] = data[fn] 286 data['seconds'] += fractional_seconds 287 have_kw_update = True 288 elif isinstance(text, cls): 289 data = text.durationData().copy() 290 negative_duration = text.negativeDuration() 291 elif isinstance(text, datetime.timedelta): 292 data = { 'days' : text.days, 293 'seconds' : text.seconds + (text.microseconds / 1000000.0) } 294 negative_duration = (0 > data['days']) 295 if negative_duration: 296 if 0.0 == data['seconds']: 297 data['days'] = - data['days'] 298 else: 299 data['days'] = 1 - data['days'] 300 data['seconds'] = 24 * 60 * 60.0 - data['seconds'] 301 data['minutes'] = 0 302 data['hours'] = 0 303 elif isinstance(text, six.integer_types) and (1 < len(args)): 304 # Apply the arguments as in the underlying Python constructor 305 data = dict(zip(cls.__PythonFields[:len(args)], args)) 306 negative_duration = False 307 else: 308 raise SimpleTypeValueError(cls, text) 309 if not have_kw_update: 310 rem_time = data.pop('seconds', 0) 311 if (0 != (rem_time % 1)): 312 data['microseconds'] = data.pop('microseconds', 0) + six.int_type(1000000 * (rem_time % 1)) 313 rem_time = rem_time // 1 314 data['seconds'] = rem_time % 60 315 rem_time = data.pop('minutes', 0) + (rem_time // 60) 316 data['minutes'] = rem_time % 60 317 rem_time = data.pop('hours', 0) + (rem_time // 60) 318 data['hours'] = rem_time % 24 319 data['days'] += (rem_time // 24) 320 for fn in cls.__PythonFields: 321 if fn in data: 322 if negative_duration: 323 kw[fn] = - data[fn] 324 else: 325 kw[fn] = data[fn] 326 else: 327 kw.pop(fn, None) 328 kw['microseconds'] = data.pop('microseconds', 0) 329 data['seconds'] += kw['microseconds'] / 1000000.0 330 331 rv = super(duration, cls).__new__(cls, **kw) 332 rv.__durationData = data 333 rv.__negativeDuration = negative_duration 334 return rv
335 336 @classmethod
337 - def XsdLiteral (cls, value):
338 elts = [] 339 if value.negativeDuration(): 340 elts.append('-') 341 elts.append('P') 342 for k in ( 'years', 'months', 'days' ): 343 v = value.__durationData.get(k, 0) 344 if 0 != v: 345 elts.append('%d%s' % (v, k[0].upper())) 346 time_elts = [] 347 for k in ( 'hours', 'minutes' ): 348 v = value.__durationData.get(k, 0) 349 if 0 != v: 350 time_elts.append('%d%s' % (v, k[0].upper())) 351 v = value.__durationData.get('seconds', 0) 352 if 0 != v: 353 time_elts.append('%gS' % (v,)) 354 if 0 < len(time_elts): 355 elts.append('T') 356 elts.extend(time_elts) 357 return ''.join(elts)
358 359 _PrimitiveDatatypes.append(duration)
360 361 -class _PyXBDateTime_base (basis.simpleTypeDefinition, basis._RepresentAsXsdLiteral_mixin):
362 363 _Lexical_fmt = None 364 """Format for the lexical representation of a date-related instance, excluding timezone. 365 366 Subclasses must define this.""" 367 368 # Map from strptime/strftime formats to the regular expressions we 369 # use to extract them. We're more strict than strptime, so not 370 # trying to use that. 371 __PatternMap = { '%Y' : '(?P<negYear>-?)(?P<year>\d{4,})' 372 , '%m' : '(?P<month>\d{2})' 373 , '%d' : '(?P<day>\d{2})' 374 , '%H' : '(?P<hour>\d{2})' 375 , '%M' : '(?P<minute>\d{2})' 376 , '%S' : '(?P<second>\d{2})(?P<fracsec>\.\d+)?' 377 , '%Z' : '(?P<tzinfo>Z|[-+]\d\d:\d\d)' } 378 379 # Cache of compiled regular expressions to parse lexical space of 380 # a subclass. 381 __LexicalREMap = { } 382 383 # Fields extracted by parsing that have an integer value 384 __LexicalIntegerFields = ( 'year', 'month', 'day', 'hour', 'minute', 'second' ) 385 386 _UTCTimeZone = pyxb.utils.utility.UTCOffsetTimeZone(0) 387 """A L{datetime.tzinfo} instance representing UTC.""" 388 389 _LocalTimeZone = pyxb.utils.utility.LocalTimeZone() 390 """A L{datetime.tzinfo} instance representing the local time zone.""" 391 392 _DefaultYear = 1900 393 _DefaultMonth = 1 394 _DefaultDay = 1 395 396 @classmethod
397 - def _LexicalToKeywords (cls, text):
398 lexical_re = cls.__LexicalREMap.get(cls) 399 if lexical_re is None: 400 pattern = '^' + cls._Lexical_fmt + '%Z?$' 401 for (k, v) in six.iteritems(cls.__PatternMap): 402 pattern = pattern.replace(k, v) 403 lexical_re = re.compile(pattern) 404 cls.__LexicalREMap[cls] = lexical_re 405 match = lexical_re.match(text) 406 if match is None: 407 raise SimpleTypeValueError(cls, text) 408 match_map = match.groupdict() 409 kw = { } 410 for (k, v) in six.iteritems(match_map): 411 if (k in cls.__LexicalIntegerFields) and (v is not None): 412 kw[k] = six.int_type(v) 413 if '-' == match_map.get('negYear'): 414 kw['year'] = - kw['year'] 415 if match_map.get('fracsec') is not None: 416 kw['microsecond'] = six.int_type(round(1000000 * six.float_type('0%s' % (match_map['fracsec'],)))) 417 else: 418 # Discard any bogosity passed in by the caller 419 kw.pop('microsecond', None) 420 if match_map.get('tzinfo') is not None: 421 kw['tzinfo'] = pyxb.utils.utility.UTCOffsetTimeZone(match_map['tzinfo']) 422 else: 423 kw.pop('tzinfo', None) 424 return kw
425 426 @classmethod
427 - def _SetKeysFromPython_csc (cls, python_value, kw, fields):
428 for f in fields: 429 kw[f] = getattr(python_value, f) 430 return getattr(super(_PyXBDateTime_base, cls), '_SetKeysFromPython_csc', lambda *a,**kw: None)(python_value, kw, fields)
431 432 @classmethod
433 - def _SetKeysFromPython (cls, python_value, kw, fields):
434 return cls._SetKeysFromPython_csc(python_value, kw, fields)
435 436 # Several datetime classes are extension classes, and the PyXB 437 # subclasses won't recognize the packed values. Use the lexical 438 # representation instead.
439 - def __reduce__ (self):
440 return (self.__class__, (self.xsdLiteral(),))
441 442 @classmethod
443 - def _AdjustForTimezone (cls, kw):
444 """Update datetime keywords to account for timezone effects. 445 446 All XML schema timezoned times are in UTC, with the time "in 447 its timezone". If the keywords indicate a non-UTC timezone is 448 in force, and L{pyxb.PreserveInputTimeZone()} has not been 449 set, adjust the values to account for the zone by subtracting 450 the corresponding UTC offset and mark explicitly that the time 451 is in UTC by leaving a C{tzinfo} attribute identifying the UTC 452 time zone. 453 454 @param kw: A dictionary of keywords relevant for a date or 455 time instance. The dictionary is updated by this call. 456 """ 457 if pyxb.PreserveInputTimeZone(): 458 return 459 tzoffs = kw.pop('tzinfo', None) 460 if tzoffs is not None: 461 use_kw = kw.copy() 462 # Ensure ctor requirements of datetime.datetime are met 463 use_kw.setdefault('year', cls._DefaultYear) 464 use_kw.setdefault('month', cls._DefaultMonth) 465 use_kw.setdefault('day', cls._DefaultDay) 466 dt = datetime.datetime(tzinfo=tzoffs, **use_kw) 467 dt -= tzoffs.utcoffset(dt) 468 for k in six.iterkeys(kw): 469 kw[k] = getattr(dt, k) 470 kw['tzinfo'] = cls._UTCTimeZone
471 472 @classmethod
473 - def XsdLiteral (cls, value):
474 iso = value.replace(tzinfo=None).isoformat() 475 if 0 <= iso.find('.'): 476 iso = iso.rstrip('0') 477 if value.tzinfo is not None: 478 iso += value.tzinfo.tzname(value) 479 return iso
480
481 -class dateTime (_PyXBDateTime_base, datetime.datetime):
482 """XMLSchema datatype U{dateTime<http://www.w3.org/TR/xmlschema-2/#dateTime>}. 483 484 This class uses the Python C{datetime.datetime} class as its 485 underlying representation. Unless L{pyxb.PreserveInputTimeZone()} 486 is used, all timezoned dateTime objects are in UTC. Presence of 487 time zone information in the lexical space is preserved by a 488 non-empty tzinfo field, which should always be zero minutes offset 489 from UTC unless the input time zone was preserved. 490 491 @warning: The value space of Python's C{datetime.datetime} class 492 is more restricted than that of C{xs:datetime}. As a specific 493 example, Python does not support negative years or years with more 494 than four digits. For now, the convenience of having an object 495 that is compatible with Python is more important than supporting 496 the full value space. In the future, the choice may be left up to 497 the developer. 498 """ 499 500 _XsdBaseType = anySimpleType 501 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('dateTime') 502 503 _Lexical_fmt = '%Y-%m-%dT%H:%M:%S' 504 __CtorFields = ( 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzinfo' ) 505
506 - def __new__ (cls, *args, **kw):
507 args = cls._ConvertArguments(args, kw) 508 509 ctor_kw = { } 510 if kw.get('_nil'): 511 ctor_kw = { 'year': 1900, 'month': 1, 'day': 1 } 512 elif 1 == len(args): 513 value = args[0] 514 if isinstance(value, six.string_types): 515 ctor_kw.update(cls._LexicalToKeywords(value)) 516 elif isinstance(value, datetime.datetime): 517 cls._SetKeysFromPython(value, ctor_kw, cls.__CtorFields) 518 elif isinstance(value, six.integer_types): 519 raise TypeError('function takes at least 3 arguments (%d given)' % (len(args),)) 520 else: 521 raise SimpleTypeValueError(cls, value) 522 elif 3 <= len(args): 523 for fi in range(len(cls.__CtorFields)): 524 fn = cls.__CtorFields[fi] 525 if fi < len(args): 526 ctor_kw[fn] = args[fi] 527 elif fn in kw: 528 ctor_kw[fn] = kw[fn] 529 kw.pop(fn, None) 530 else: 531 raise TypeError('function takes at least 3 arguments (%d given)' % (len(args),)) 532 533 cls._AdjustForTimezone(ctor_kw) 534 kw.update(ctor_kw) 535 year = kw.pop('year') 536 month = kw.pop('month') 537 day = kw.pop('day') 538 rv = super(dateTime, cls).__new__(cls, year, month, day, **kw) 539 return rv
540 541 @classmethod
542 - def today (cls):
543 """Return today. 544 545 Just like datetime.datetime.today(), except this one sets a 546 tzinfo field so it's clear the value is UTC.""" 547 return cls(datetime.datetime.now(cls._UTCTimeZone))
548
549 - def aslocal (self):
550 """Returns a C{datetime.datetime} instance denoting the same 551 time as this instance but adjusted to be in the local time 552 zone. 553 554 @rtype: C{datetime.datetime} (B{NOT} C{xsd.dateTime}) 555 """ 556 dt = self 557 if dt.tzinfo is None: 558 dt = dt.replace(tzinfo=self._UTCTimeZone) 559 return dt.astimezone(self._LocalTimeZone)
560 561 _PrimitiveDatatypes.append(dateTime)
562 563 -class time (_PyXBDateTime_base, datetime.time):
564 """XMLSchema datatype U{time<http://www.w3.org/TR/xmlschema-2/#time>}. 565 566 This class uses the Python C{datetime.time} class as its 567 underlying representation. Note that per the XMLSchema spec, all 568 dateTime objects are in UTC, and that timezone information in the 569 string representation in XML is an indication of the local time 570 zone's offset from UTC. Presence of time zone information in the 571 lexical space is indicated by the tzinfo field. 572 573 @note: C{pyxb.PreserveInputTimeZone()} can be used to bypass the 574 normalization to UTC. 575 """ 576 577 _XsdBaseType = anySimpleType 578 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('time') 579 580 _Lexical_fmt = '%H:%M:%S' 581 __CtorFields = ( 'hour', 'minute', 'second', 'microsecond', 'tzinfo' ) 582
583 - def __new__ (cls, *args, **kw):
584 args = cls._ConvertArguments(args, kw) 585 ctor_kw = { } 586 if 1 <= len(args): 587 value = args[0] 588 if isinstance(value, six.string_types): 589 ctor_kw.update(cls._LexicalToKeywords(value)) 590 elif isinstance(value, (datetime.time, datetime.datetime)): 591 cls._SetKeysFromPython(value, ctor_kw, cls.__CtorFields) 592 elif isinstance(value, six.integer_types): 593 for fi in range(len(cls.__CtorFields)): 594 fn = cls.__CtorFields[fi] 595 if fi < len(args): 596 ctor_kw[fn] = args[fi] 597 elif fn in kw: 598 ctor_kw[fn] = kw[fn] 599 kw.pop(fn, None) 600 else: 601 raise SimpleTypeValueError(cls, value) 602 603 cls._AdjustForTimezone(ctor_kw) 604 kw.update(ctor_kw) 605 return super(time, cls).__new__(cls, **kw)
606 607 _PrimitiveDatatypes.append(time)
608 609 -class _PyXBDateOnly_base (_PyXBDateTime_base, datetime.datetime):
610 _XsdBaseType = anySimpleType 611 612 _ValidFields = ( 'year', 'month', 'day' ) 613
614 - def __new__ (cls, *args, **kw):
615 args = cls._ConvertArguments(args, kw) 616 ctor_kw = { } 617 ctor_kw['year'] = cls._DefaultYear 618 ctor_kw['month'] = cls._DefaultMonth 619 ctor_kw['day'] = cls._DefaultDay 620 ctor_kw['hour'] = 0 621 ctor_kw['minute'] = 0 622 ctor_kw['second'] = 0 623 if kw.get('_nil'): 624 pass 625 elif 1 <= len(args): 626 value = args[0] 627 if isinstance(value, six.string_types): 628 if 1 != len(args): 629 raise TypeError('construction from string requires exactly 1 argument') 630 ctor_kw.update(cls._LexicalToKeywords(value)) 631 elif isinstance(value, (datetime.date, datetime.datetime)): 632 if 1 != len(args): 633 raise TypeError('construction from instance requires exactly 1 argument') 634 cls._SetKeysFromPython(value, ctor_kw, cls._ValidFields) 635 try: 636 tzinfo = value.tzinfo 637 if tzinfo is not None: 638 ctor_kw['tzinfo'] = tzinfo 639 except AttributeError: 640 pass 641 else: 642 fi = 0 643 while fi < len(cls._ValidFields): 644 fn = cls._ValidFields[fi] 645 if fi < len(args): 646 ctor_kw[fn] = args[fi] 647 elif fn in kw: 648 ctor_kw[fn] = kw[fn] 649 kw.pop(fn, None) 650 fi += 1 651 if fi < len(args): 652 ctor_kw['tzinfo'] = args[fi] 653 fi += 1 654 if fi != len(args): 655 raise TypeError('function takes %d arguments plus optional tzinfo (%d given)' % (len(cls._ValidFields), len(args))) 656 else: 657 raise TypeError('function takes %d arguments plus optional tzinfo' % (len(cls._ValidFields),)) 658 659 # Do not adjust for the timezone here. Only xsd:date provides 660 # a recoverable timezone, so just preserve the as-supplied 661 # timezone, and we'll canonicalize the date one if/when it's 662 # converted back to lexical form. 663 kw.update(ctor_kw) 664 argv = [] 665 argv.append(kw.pop('year')) 666 argv.append(kw.pop('month')) 667 argv.append(kw.pop('day')) 668 return super(_PyXBDateOnly_base, cls).__new__(cls, *argv, **kw)
669 670 @classmethod
671 - def XsdLiteral (cls, value):
672 # Work around strftime year restriction 673 fmt = cls._Lexical_fmt 674 if value.year < 1900: 675 fmt = fmt.replace('%Y', '%04d' % (value.year,)) 676 value = value.replace(year=1900) 677 if value.tzinfo is not None: 678 fmt += value.tzinfo.tzname(value) 679 return value.strftime(fmt)
680
681 -class date (_PyXBDateOnly_base):
682 """XMLSchema datatype U{date<http://www.w3.org/TR/xmlschema-2/#date>}. 683 684 This class uses the Python C{datetime.datetime} class as its 685 underlying representation; fields not relevant to this type are 686 derived from 1900-01-01T00:00:00. 687 688 @note: Unlike L{dateTime}, timezoned date values are not converted 689 to UTC. The provided timezone information is retained along with 690 the instance; however, the lexical representation generated for 691 output is canonicalized (timezones no more than 12 hours off UTC). 692 """ 693 694 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('date') 695 _Lexical_fmt = '%Y-%m-%d' 696 _Fields = ( 'year', 'month', 'day' ) 697 698 __SecondsPerMinute = 60 699 __MinutesPerHalfDay = 12 * 60 700 __MinutesPerDay = 24 * 60
701 - def xsdRecoverableTzinfo (self):
702 """Return the recoverable tzinfo for the date. 703 704 Return a L{pyxb.utils.utility.UTCOffsetTimeZone} instance 705 reflecting the timezone associated with the date, or C{None} 706 if the date is not timezoned. 707 708 @note: This is not the recoverable timezone, because timezones are 709 represented as timedeltas which get normalized in ways that 710 don't match what we expect for a tzinfo. 711 """ 712 if self.tzinfo is None: 713 return None 714 sdt = self.replace(hour=0, minute=0, second=0, tzinfo=self._UTCTimeZone) 715 utc_offset = (sdt - self).seconds // self.__SecondsPerMinute 716 if utc_offset > self.__MinutesPerHalfDay: 717 utc_offset -= self.__MinutesPerDay 718 return pyxb.utils.utility.UTCOffsetTimeZone(utc_offset)
719 720 @classmethod
721 - def XsdLiteral (cls, value):
722 # Work around strftime year restriction 723 fmt = cls._Lexical_fmt 724 rtz = value.xsdRecoverableTzinfo() 725 if rtz is not None: 726 # If the date is timezoned, convert it to UTC 727 value -= value.tzinfo.utcoffset(value) 728 value = value.replace(tzinfo=cls._UTCTimeZone) 729 # Use the midpoint of the one-day interval to get the correct 730 # month/day. 731 value += datetime.timedelta(minutes=cls.__MinutesPerHalfDay) 732 if value.year < 1900: 733 fmt = fmt.replace('%Y', '%04d' % (value.year,)) 734 value = value.replace(year=1900) 735 if rtz is not None: 736 fmt += rtz.tzname(value) 737 return value.strftime(fmt)
738 739 _PrimitiveDatatypes.append(date)
740 741 -class gYearMonth (_PyXBDateOnly_base):
742 """XMLSchema datatype U{gYearMonth<http://www.w3.org/TR/xmlschema-2/#gYearMonth>}. 743 744 This class uses the Python C{datetime.datetime} class as its 745 underlying representation; fields not relevant to this type are 746 derived from 1900-01-01T00:00:00. 747 """ 748 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('gYearMonth') 749 _Lexical_fmt = '%Y-%m' 750 _ValidFields = ( 'year', 'month' )
751 752 _PrimitiveDatatypes.append(gYearMonth)
753 754 -class gYear (_PyXBDateOnly_base):
755 """XMLSchema datatype U{gYear<http://www.w3.org/TR/xmlschema-2/#gYear>}. 756 757 This class uses the Python C{datetime.datetime} class as its 758 underlying representation; fields not relevant to this type are 759 derived from 1900-01-01T00:00:00. 760 """ 761 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('gYear') 762 _Lexical_fmt = '%Y' 763 _ValidFields = ( 'year', )
764 _PrimitiveDatatypes.append(gYear)
765 766 -class gMonthDay (_PyXBDateOnly_base):
767 """XMLSchema datatype U{gMonthDay<http://www.w3.org/TR/xmlschema-2/#gMonthDay>}. 768 769 This class uses the Python C{datetime.datetime} class as its 770 underlying representation; fields not relevant to this type are 771 derived from 1900-01-01T00:00:00. 772 """ 773 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('gMonthDay') 774 _Lexical_fmt = '--%m-%d' 775 _ValidFields = ( 'month', 'day' )
776 _PrimitiveDatatypes.append(gMonthDay)
777 778 -class gDay (_PyXBDateOnly_base):
779 """XMLSchema datatype U{gDay<http://www.w3.org/TR/xmlschema-2/#gDay>}. 780 781 This class uses the Python C{datetime.datetime} class as its 782 underlying representation; fields not relevant to this type are 783 derived from 1900-01-01T00:00:00. 784 """ 785 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('gDay') 786 _Lexical_fmt = '---%d' 787 _ValidFields = ( 'day', )
788 _PrimitiveDatatypes.append(gDay)
789 790 -class gMonth (_PyXBDateOnly_base):
791 """XMLSchema datatype U{gMonth<http://www.w3.org/TR/xmlschema-2/#gMonth>}. 792 793 This class uses the Python C{datetime.datetime} class as its 794 underlying representation; fields not relevant to this type are 795 derived from 1900-01-01T00:00:00. 796 """ 797 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('gMonth') 798 _Lexical_fmt = '--%m' 799 _ValidFields = ( 'month', )
800 _PrimitiveDatatypes.append(gMonth)
801 802 -class hexBinary (basis.simpleTypeDefinition, six.binary_type):
803 """XMLSchema datatype U{hexBinary<http://www.w3.org/TR/xmlschema-2/#hexBinary>}.""" 804 _XsdBaseType = anySimpleType 805 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('hexBinary') 806 807 @classmethod
808 - def _ConvertArguments_vx (cls, args, kw):
809 if kw.get('_from_xml', False): 810 xmlt = args[0] 811 try: 812 xmld = xmlt.encode('utf-8') 813 arg0 = binascii.unhexlify(xmld) 814 args = (arg0,) + args[1:] 815 except (TypeError, binascii.Error): 816 raise SimpleTypeValueError(cls, args[0]) 817 return args
818 819 @classmethod
820 - def XsdLiteral (cls, value):
821 if isinstance(value, six.text_type): 822 value = value.encode('utf-8') 823 rvd = binascii.hexlify(value) 824 rvt = rvd.decode('utf-8') 825 return rvt.upper()
826 827 @classmethod
828 - def XsdValueLength (cls, value):
829 return len(value)
830 831 _PrimitiveDatatypes.append(hexBinary)
832 833 -class base64Binary (basis.simpleTypeDefinition, six.binary_type):
834 """XMLSchema datatype U{base64Binary<http://www.w3.org/TR/xmlschema-2/#base64Binary>}. 835 836 See also U{RFC2045<http://tools.ietf.org/html/rfc2045>} and U{RFC4648<http://tools.ietf.org/html/rfc4648>}. 837 """ 838 _XsdBaseType = anySimpleType 839 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('base64Binary') 840 841 # base64 is too lenient: it accepts 'ZZZ=' as an encoding of 'e', while 842 # the required XML Schema production requires 'ZQ=='. Define a regular 843 # expression per section 3.2.16. 844 _B04 = '[AQgw]' 845 _B04S = '(%s ?)' % (_B04,) 846 _B16 = '[AEIMQUYcgkosw048]' 847 _B16S = '(%s ?)' % (_B16,) 848 _B64 = '[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/]' 849 _B64S = '(%s ?)' % (_B64,) 850 851 __Pattern = '^((' + _B64S + '{4})*((' + _B64S + '{3}' + _B64 + ')|(' + _B64S + '{2}' + _B16S + '=)|(' + _B64S + _B04S + '= ?=)))?$' 852 __Lexical_re = re.compile(__Pattern) 853 854 @classmethod
855 - def _ConvertArguments_vx (cls, args, kw):
856 if kw.get('_from_xml', False): 857 xmlt = args[0] 858 try: 859 xmld = xmlt.encode('utf-8') 860 arg0 = base64.standard_b64decode(xmld) 861 args = (arg0,) + args[1:] 862 except (TypeError, binascii.Error): 863 raise SimpleTypeValueError(cls, xmlt) 864 # This is what it costs to try to be a validating processor. 865 if cls.__Lexical_re.match(xmlt) is None: 866 raise SimpleTypeValueError(cls, xmlt) 867 return args
868 869 @classmethod
870 - def XsdLiteral (cls, value):
871 if isinstance(value, six.text_type): 872 value = value.encode('utf-8') 873 rvd = base64.standard_b64encode(value) 874 rvt = rvd.decode('utf-8') 875 return rvt
876 877 @classmethod
878 - def XsdValueLength (cls, value):
879 return len(value)
880 881 _PrimitiveDatatypes.append(base64Binary)
882 883 -class anyURI (basis.simpleTypeDefinition, six.text_type):
884 """XMLSchema datatype U{anyURI<http://www.w3.org/TR/xmlschema-2/#anyURI>}.""" 885 _XsdBaseType = anySimpleType 886 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('anyURI') 887 888 @classmethod
889 - def XsdValueLength (cls, value):
890 return len(value)
891 892 @classmethod
893 - def XsdLiteral (cls, value):
894 return six.text_type(value)
895 896 _PrimitiveDatatypes.append(anyURI)
897 898 -class QName (basis.simpleTypeDefinition, pyxb.namespace.ExpandedName):
899 """XMLSchema datatype U{QName<http://www.w3.org/TR/xmlschema-2/#QName>}.""" 900 _XsdBaseType = anySimpleType 901 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('QName') 902 903 @classmethod
904 - def XsdValueLength (cls, value):
905 """Section 4.3.1.3: Legacy length return None to indicate no check""" 906 return None
907 908 @classmethod
909 - def _ConvertIf (cls, value, xmlns_context):
910 if isinstance(value, pyxb.namespace.ExpandedName): 911 assert 0 > value.localName().find(':') 912 return value 913 if not isinstance(value, six.string_types): 914 raise SimpleTypeValueError(cls, value) 915 if 0 <= value.find(':'): 916 (prefix, local) = value.split(':', 1) 917 if (NCName._ValidRE.match(prefix) is None) or (NCName._ValidRE.match(local) is None): 918 raise SimpleTypeValueError(cls, value) 919 if xmlns_context is None: 920 raise pyxb.QNameResolutionError('QName resolution requires namespace context', value, xmlns_context) 921 return xmlns_context.interpretQName(value, default_no_namespace=True) 922 if NCName._ValidRE.match(value) is None: 923 raise SimpleTypeValueError(cls, value) 924 if xmlns_context is not None: 925 return xmlns_context.interpretQName(value, default_no_namespace=True) 926 return pyxb.namespace.ExpandedName(value)
927 928 @classmethod
929 - def _ConvertArguments_vx (cls, args, kw):
930 if 1 == len(args): 931 xmlns_context = kw.pop('_xmlns_context', pyxb.namespace.NamespaceContext.Current()) 932 args = (cls._ConvertIf(args[0], xmlns_context),) 933 super_fn = getattr(super(QName, cls), '_ConvertArguments_vx', lambda *a,**kw: args) 934 return super_fn(args, kw)
935 936 @classmethod
937 - def XsdLiteral (cls, value):
938 # A QName has no unicode/XSD representation in the absence of 939 # a registered namespace. Whatever called this should have 940 # detected that the value is a QName and used 941 # BindingDOMSupport.qnameToText() to convert it to a lexical 942 # representation that incorporates a declared namespace. 943 raise pyxb.UsageError('Cannot represent QName without namespace declaration')
944 945 @classmethod
946 - def _XsdConstraintsPreCheck_vb (cls, value):
947 super_fn = getattr(super(QName, cls), '_XsdConstraintsPreCheck_vb', lambda *a,**kw: True) 948 return super_fn(cls._ConvertIf(value, pyxb.namespace.NamespaceContext.Current()))
949 950 951 _PrimitiveDatatypes.append(QName)
952 953 -class NOTATION (basis.simpleTypeDefinition):
954 """XMLSchema datatype U{NOTATION<http://www.w3.org/TR/xmlschema-2/#NOTATION>}.""" 955 _XsdBaseType = anySimpleType 956 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('NOTATION') 957 958 @classmethod
959 - def XsdValueLength (cls, value):
960 """Section 4.3.1.3: Legacy length return None to indicate no check""" 961 return None
962 963 _PrimitiveDatatypes.append(NOTATION)
964 965 -class normalizedString (string):
966 """XMLSchema datatype U{normalizedString<http:///www.w3.org/TR/xmlschema-2/#normalizedString>}. 967 968 Normalized strings can't have carriage returns, linefeeds, or 969 tabs in them.""" 970 971 # All descendents of normalizedString constrain the lexical/value 972 # space in some way. Subclasses should set the _ValidRE class 973 # variable to a compiled regular expression that matches valid 974 # input, or the _InvalidRE class variable to a compiled regular 975 # expression that detects invalid inputs. 976 # 977 # Alternatively, subclasses can override the _ValidateString_va 978 # method. 979 980 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('normalizedString') 981 982 # @todo Implement pattern constraints and just rely on them 983 984 # No CR, LF, or TAB 985 __BadChars = re.compile("[\r\n\t]") 986 987 _ValidRE = None 988 _InvalidRE = None 989 990 @classmethod
991 - def __ValidateString (cls, value):
992 # This regular expression doesn't work. Don't know why. 993 #if cls.__BadChars.match(value) is not None: 994 # raise SimpleTypeValueError('CR/NL/TAB characters illegal in %s' % (cls.__name__,)) 995 if (0 <= value.find("\n")) or (0 <= value.find("\r")) or (0 <= value.find("\t")): 996 raise SimpleTypeValueError(cls, value) 997 if cls._ValidRE is not None: 998 match_object = cls._ValidRE.match(value) 999 if match_object is None: 1000 raise SimpleTypeValueError(cls, value) 1001 if cls._InvalidRE is not None: 1002 match_object = cls._InvalidRE.match(value) 1003 if not (match_object is None): 1004 raise SimpleTypeValueError(cls, value) 1005 return True
1006 1007 @classmethod
1008 - def _ValidateString_va (cls, value):
1009 """Post-extended method to validate that a string matches a given pattern. 1010 1011 If you can express the valid strings as a compiled regular 1012 expression in the class variable _ValidRE, or the invalid 1013 strings as a compiled regular expression in the class variable 1014 _InvalidRE, you can just use those. If the acceptable matches 1015 are any trickier, you should invoke the superclass 1016 implementation, and if it returns True then perform additional 1017 tests.""" 1018 super_fn = getattr(super(normalizedString, cls), '_ValidateString_va', lambda *a,**kw: True) 1019 if not super_fn(value): 1020 return False 1021 return cls.__ValidateString(value)
1022 1023 @classmethod
1024 - def _XsdConstraintsPreCheck_vb (cls, value):
1025 if not isinstance(value, six.string_types): 1026 raise SimpleTypeValueError(cls, value) 1027 if not cls._ValidateString_va(value): 1028 raise SimpleTypeValueError(cls, value) 1029 super_fn = getattr(super(normalizedString, cls), '_XsdConstraintsPreCheck_vb', lambda *a,**kw: True) 1030 return super_fn(value)
1031 1032 _DerivedDatatypes.append(normalizedString) 1033 assert normalizedString.XsdSuperType() == string
1034 1035 -class token (normalizedString):
1036 """XMLSchema datatype U{token<http:///www.w3.org/TR/xmlschema-2/#token>}. 1037 1038 Tokens cannot leading or trailing space characters; any 1039 carriage return, line feed, or tab characters; nor any occurrence 1040 of two or more consecutive space characters.""" 1041 1042 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('token') 1043 1044 @classmethod
1045 - def _ValidateString_va (cls, value):
1046 super_fn = getattr(super(token, cls), '_ValidateString_va', lambda *a,**kw: True) 1047 if not super_fn(value): 1048 return False 1049 if value.startswith(" ") \ 1050 or value.endswith(" ") \ 1051 or (0 <= value.find(' ')): 1052 raise SimpleTypeValueError(cls, value) 1053 return True
1054 _DerivedDatatypes.append(token)
1055 1056 -class language (token):
1057 """XMLSchema datatype U{language<http:///www.w3.org/TR/xmlschema-2/#language>}""" 1058 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('language') 1059 _ValidRE = re.compile('^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$')
1060 _DerivedDatatypes.append(language)
1061 1062 -class NMTOKEN (token):
1063 """XMLSchema datatype U{NMTOKEN<http:///www.w3.org/TR/xmlschema-2/#NMTOKEN>}. 1064 1065 See U{http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#NT-Nmtoken}. 1066 1067 NMTOKEN is an identifier that can start with any character that is 1068 legal in it.""" 1069 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('NMTOKEN') 1070 _ValidRE = pyxb.utils.unicode.XML1p0e2.NmToken_re
1071 _DerivedDatatypes.append(NMTOKEN)
1072 1073 -class NMTOKENS (basis.STD_list):
1074 _ItemType = NMTOKEN
1075 _ListDatatypes.append(NMTOKENS)
1076 1077 -class Name (token):
1078 """XMLSchema datatype U{Name<http:///www.w3.org/TR/xmlschema-2/#Name>}. 1079 1080 See U{http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#NT-Name}.""" 1081 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('Name') 1082 _ValidRE = pyxb.utils.unicode.XML1p0e2.Name_re
1083 _DerivedDatatypes.append(Name)
1084 1085 -class NCName (Name):
1086 """XMLSchema datatype U{NCName<http:///www.w3.org/TR/xmlschema-2/#NCName>}. 1087 1088 See U{http://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-NCName}.""" 1089 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('NCName') 1090 _ValidRE = pyxb.utils.unicode.XML1p0e2.NCName_re
1091 _DerivedDatatypes.append(NCName)
1092 1093 -class ID (NCName):
1094 """XMLSchema datatype U{ID<http:///www.w3.org/TR/xmlschema-2/#ID>}.""" 1095 # Lexical and value space match that of parent NCName 1096 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('ID') 1097 pass
1098 _DerivedDatatypes.append(ID)
1099 1100 -class IDREF (NCName):
1101 """XMLSchema datatype U{IDREF<http:///www.w3.org/TR/xmlschema-2/#IDREF>}.""" 1102 # Lexical and value space match that of parent NCName 1103 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('IDREF') 1104 pass
1105 _DerivedDatatypes.append(IDREF)
1106 1107 -class IDREFS (basis.STD_list):
1108 """XMLSchema datatype U{IDREFS<http:///www.w3.org/TR/xmlschema-2/#IDREFS>}.""" 1109 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('IDREFS') 1110 _ItemType = IDREF
1111 _ListDatatypes.append(IDREFS)
1112 1113 -class ENTITY (NCName):
1114 """XMLSchema datatype U{ENTITY<http:///www.w3.org/TR/xmlschema-2/#ENTITY>}.""" 1115 # Lexical and value space match that of parent NCName; we're gonna 1116 # ignore the additional requirement that it be declared as an 1117 # unparsed entity 1118 # 1119 # @todo Don't ignore the requirement that this be declared as an 1120 # unparsed entity. 1121 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('ENTITY') 1122 pass
1123 _DerivedDatatypes.append(ENTITY)
1124 1125 -class ENTITIES (basis.STD_list):
1126 """XMLSchema datatype U{ENTITIES<http:///www.w3.org/TR/xmlschema-2/#ENTITIES>}.""" 1127 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('ENTITIES') 1128 _ItemType = ENTITY
1129 _ListDatatypes.append(ENTITIES)
1130 1131 -class integer (basis.simpleTypeDefinition, six.long_type):
1132 """XMLSchema datatype U{integer<http://www.w3.org/TR/xmlschema-2/#integer>}.""" 1133 _XsdBaseType = decimal 1134 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('integer') 1135 1136 @classmethod
1137 - def XsdLiteral (cls, value):
1138 return '%d' % (value,)
1139 1140 _DerivedDatatypes.append(integer)
1141 1142 -class nonPositiveInteger (integer):
1143 """XMLSchema datatype U{nonPositiveInteger<http://www.w3.org/TR/xmlschema-2/#nonPositiveInteger>}.""" 1144 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('nonPositiveInteger')
1145 _DerivedDatatypes.append(nonPositiveInteger)
1146 1147 -class negativeInteger (nonPositiveInteger):
1148 """XMLSchema datatype U{negativeInteger<http://www.w3.org/TR/xmlschema-2/#negativeInteger>}.""" 1149 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('negativeInteger')
1150 _DerivedDatatypes.append(negativeInteger)
1151 1152 -class long (integer):
1153 """XMLSchema datatype U{long<http://www.w3.org/TR/xmlschema-2/#long>}.""" 1154 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('long')
1155 _DerivedDatatypes.append(long)
1156 1157 -class int (basis.simpleTypeDefinition, six.int_type):
1158 """XMLSchema datatype U{int<http://www.w3.org/TR/xmlschema-2/#int>}.""" 1159 _XsdBaseType = long 1160 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('int') 1161 1162 @classmethod
1163 - def XsdLiteral (cls, value):
1164 return '%s' % (value,)
1165 1166 pass
1167 _DerivedDatatypes.append(int)
1168 1169 -class short (int):
1170 """XMLSchema datatype U{short<http://www.w3.org/TR/xmlschema-2/#short>}.""" 1171 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('short')
1172 _DerivedDatatypes.append(short)
1173 1174 -class byte (short):
1175 """XMLSchema datatype U{byte<http://www.w3.org/TR/xmlschema-2/#byte>}.""" 1176 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('byte')
1177 _DerivedDatatypes.append(byte)
1178 1179 -class nonNegativeInteger (integer):
1180 """XMLSchema datatype U{nonNegativeInteger<http://www.w3.org/TR/xmlschema-2/#nonNegativeInteger>}.""" 1181 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('nonNegativeInteger')
1182 _DerivedDatatypes.append(nonNegativeInteger)
1183 1184 -class unsignedLong (nonNegativeInteger):
1185 """XMLSchema datatype U{unsignedLong<http://www.w3.org/TR/xmlschema-2/#unsignedLong>}.""" 1186 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('unsignedLong')
1187 _DerivedDatatypes.append(unsignedLong)
1188 1189 -class unsignedInt (unsignedLong):
1190 """XMLSchema datatype U{unsignedInt<http://www.w3.org/TR/xmlschema-2/#unsignedInt>}.""" 1191 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('unsignedInt')
1192 _DerivedDatatypes.append(unsignedInt)
1193 1194 -class unsignedShort (unsignedInt):
1195 """XMLSchema datatype U{unsignedShort<http://www.w3.org/TR/xmlschema-2/#unsignedShort>}.""" 1196 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('unsignedShort')
1197 _DerivedDatatypes.append(unsignedShort)
1198 1199 -class unsignedByte (unsignedShort):
1200 """XMLSchema datatype U{unsignedByte<http://www.w3.org/TR/xmlschema-2/#unsignedByte>}.""" 1201 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('unsignedByte')
1202 _DerivedDatatypes.append(unsignedByte)
1203 1204 -class positiveInteger (nonNegativeInteger):
1205 """XMLSchema datatype U{positiveInteger<http://www.w3.org/TR/xmlschema-2/#positiveInteger>}.""" 1206 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('positiveInteger')
1207 _DerivedDatatypes.append(positiveInteger) 1208 1209 from . import content
1210 1211 -class anyType (basis.complexTypeDefinition):
1212 """XMLSchema datatype U{anyType<http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/#key-urType>}.""" 1213 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('anyType') 1214 _DefinitionLocation = pyxb.utils.utility.Location('http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/#key-urType', 1, 1) 1215 _ContentTypeTag = basis.complexTypeDefinition._CT_MIXED 1216 _Abstract = False 1217 _HasWildcardElement = True 1218 _AttributeWildcard = content.Wildcard(namespace_constraint=content.Wildcard.NC_any, process_contents=content.Wildcard.PC_lax)
1219
1220 -def _BuildAutomaton ():
1221 # Remove this helper function from the namespace after it's invoked 1222 global _BuildAutomaton 1223 del _BuildAutomaton 1224 import pyxb.utils.fac as fac 1225 1226 counters = set() 1227 cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/#key-urType', 1, 1)) 1228 counters.add(cc_0) 1229 states = set() 1230 final_update = set() 1231 final_update.add(fac.UpdateInstruction(cc_0, False)) 1232 symbol = content.WildcardUse(content.Wildcard(process_contents=content.Wildcard.PC_lax, namespace_constraint=content.Wildcard.NC_any), None) 1233 st_0 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) 1234 states.add(st_0) 1235 transitions = set() 1236 transitions.add(fac.Transition(st_0, [ 1237 fac.UpdateInstruction(cc_0, True) ])) 1238 st_0._set_transitionSet(transitions) 1239 return fac.Automaton(states, counters, True, containing_state=None)
1240 anyType._Automaton = _BuildAutomaton() 1241 1242 1243 # anyType._IsUrType() is True; foo._IsUrType() for descendents of it 1244 # should be false. 1245 anyType._IsUrType = classmethod(lambda _c: _c == anyType) 1246