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