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