1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
63
64
65 -class anySimpleType (basis.simpleTypeDefinition, unicode):
73
74
75
76 -class string (basis.simpleTypeDefinition, unicode):
89
90 _PrimitiveDatatypes.append(string)
91
92
93
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
101 if value:
102 return 'true'
103 return 'false'
104
106 if self:
107 return 'true'
108 return 'false'
109
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):
139
140 _PrimitiveDatatypes.append(decimal)
141
142 -class float (basis.simpleTypeDefinition, pyxb.utils.types_.FloatType):
150
151 _PrimitiveDatatypes.append(float)
152
153 -class double (basis.simpleTypeDefinition, pyxb.utils.types_.FloatType):
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
187 __XSDFields = ( 'years', 'months', 'days', 'hours', 'minutes', 'seconds' )
188 __PythonFields = ( 'days', 'seconds', 'microseconds', 'minutes', 'hours' )
189
192 __negativeDuration = None
193
196 __durationData = None
197
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
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
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
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
314
315 _PrimitiveDatatypes.append(duration)
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
325
326
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
336
337 __LexicalREMap = { }
338
339
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
381
382 @classmethod
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
391
392
393
394
397
398 @classmethod
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
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
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
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
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
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
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)
566 _XsdBaseType = anySimpleType
567
568 _ValidFields = ( 'year', 'month', 'day' )
569
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
616
617
618
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
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
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
694
695
696 _PrimitiveDatatypes.append(date)
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)
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):
787
788 _PrimitiveDatatypes.append(hexBinary)
789
790 -class base64Binary (basis.simpleTypeDefinition, pyxb.utils.types_.DataType):
837
838 _PrimitiveDatatypes.append(base64Binary)
839
840 -class anyURI (basis.simpleTypeDefinition, unicode):
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
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
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
879
885
886 @classmethod
889
890 @classmethod
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):
916
917 _PrimitiveDatatypes.append(NOTATION)
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
926
927
928
929
930
931
932
933
934 _ExpandedName = pyxb.namespace.XMLSchema.createExpandedName('normalizedString')
935
936
937
938
939 __BadChars = re.compile("[\r\n\t]")
940
941 _ValidRE = None
942 _InvalidRE = None
943
944 @classmethod
960
961 @classmethod
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
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
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)
1014 _DerivedDatatypes.append(language)
1025 _DerivedDatatypes.append(NMTOKEN)
1029 _ListDatatypes.append(NMTOKENS)
1030
1031 -class Name (token):
1037 _DerivedDatatypes.append(Name)
1045 _DerivedDatatypes.append(NCName)
1046
1047 -class ID (NCName):
1052 _DerivedDatatypes.append(ID)
1053
1054 -class IDREF (NCName):
1059 _DerivedDatatypes.append(IDREF)
1060
1061 -class IDREFS (basis.STD_list):
1065 _ListDatatypes.append(IDREFS)
1077 _DerivedDatatypes.append(ENTITY)
1083 _ListDatatypes.append(ENTITIES)
1084
1085 -class integer (basis.simpleTypeDefinition, pyxb.utils.types_.LongType):
1093
1094 _DerivedDatatypes.append(integer)
1099 _DerivedDatatypes.append(nonPositiveInteger)
1104 _DerivedDatatypes.append(negativeInteger)
1105
1106 -class long (integer):
1109 _DerivedDatatypes.append(long)
1110
1111 -class int (basis.simpleTypeDefinition, pyxb.utils.types_.IntType):
1121 _DerivedDatatypes.append(int)
1126 _DerivedDatatypes.append(short)
1127
1128 -class byte (short):
1131 _DerivedDatatypes.append(byte)
1136 _DerivedDatatypes.append(nonNegativeInteger)
1141 _DerivedDatatypes.append(unsignedLong)
1146 _DerivedDatatypes.append(unsignedInt)
1151 _DerivedDatatypes.append(unsignedShort)
1156 _DerivedDatatypes.append(unsignedByte)
1161 _DerivedDatatypes.append(positiveInteger)
1162
1163 from . import content
1164
1165 -class anyType (basis.complexTypeDefinition):
1173
1175
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
1198
1199 anyType._IsUrType = classmethod(lambda _c: _c == anyType)
1200