passagemath-objects 10.8.1a3__cp314-cp314-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (283) hide show
  1. passagemath_objects/__init__.py +3 -0
  2. passagemath_objects-10.8.1a3.dist-info/DELVEWHEEL +2 -0
  3. passagemath_objects-10.8.1a3.dist-info/METADATA +114 -0
  4. passagemath_objects-10.8.1a3.dist-info/RECORD +283 -0
  5. passagemath_objects-10.8.1a3.dist-info/WHEEL +5 -0
  6. passagemath_objects-10.8.1a3.dist-info/top_level.txt +3 -0
  7. passagemath_objects.libs/libgmp-10-60021eeab4282b29024e43b2b1412b53.dll +0 -0
  8. sage/all__sagemath_objects.py +46 -0
  9. sage/arith/all__sagemath_objects.py +5 -0
  10. sage/arith/long.pxd +411 -0
  11. sage/arith/numerical_approx.cp314-win_amd64.pyd +0 -0
  12. sage/arith/numerical_approx.pxd +35 -0
  13. sage/arith/numerical_approx.pyx +75 -0
  14. sage/arith/power.cp314-win_amd64.pyd +0 -0
  15. sage/arith/power.pxd +31 -0
  16. sage/arith/power.pyx +127 -0
  17. sage/categories/action.cp314-win_amd64.pyd +0 -0
  18. sage/categories/action.pxd +29 -0
  19. sage/categories/action.pyx +641 -0
  20. sage/categories/algebra_functor.py +745 -0
  21. sage/categories/all__sagemath_objects.py +33 -0
  22. sage/categories/basic.py +71 -0
  23. sage/categories/cartesian_product.py +292 -0
  24. sage/categories/category.py +3379 -0
  25. sage/categories/category_cy_helper.cp314-win_amd64.pyd +0 -0
  26. sage/categories/category_cy_helper.pxd +8 -0
  27. sage/categories/category_cy_helper.pyx +322 -0
  28. sage/categories/category_singleton.cp314-win_amd64.pyd +0 -0
  29. sage/categories/category_singleton.pxd +3 -0
  30. sage/categories/category_singleton.pyx +343 -0
  31. sage/categories/category_types.py +637 -0
  32. sage/categories/category_with_axiom.py +2889 -0
  33. sage/categories/covariant_functorial_construction.py +700 -0
  34. sage/categories/facade_sets.py +228 -0
  35. sage/categories/functor.cp314-win_amd64.pyd +0 -0
  36. sage/categories/functor.pxd +7 -0
  37. sage/categories/functor.pyx +659 -0
  38. sage/categories/homset.py +1289 -0
  39. sage/categories/homsets.py +364 -0
  40. sage/categories/isomorphic_objects.py +73 -0
  41. sage/categories/map.cp314-win_amd64.pyd +0 -0
  42. sage/categories/map.pxd +34 -0
  43. sage/categories/map.pyx +2106 -0
  44. sage/categories/morphism.cp314-win_amd64.pyd +0 -0
  45. sage/categories/morphism.pxd +14 -0
  46. sage/categories/morphism.pyx +895 -0
  47. sage/categories/objects.py +167 -0
  48. sage/categories/primer.py +1695 -0
  49. sage/categories/pushout.py +4847 -0
  50. sage/categories/quotients.py +64 -0
  51. sage/categories/realizations.py +200 -0
  52. sage/categories/sets_cat.py +3305 -0
  53. sage/categories/sets_with_partial_maps.py +52 -0
  54. sage/categories/subobjects.py +64 -0
  55. sage/categories/subquotients.py +21 -0
  56. sage/categories/with_realizations.py +311 -0
  57. sage/cpython/__init__.py +22 -0
  58. sage/cpython/_py2_random.py +619 -0
  59. sage/cpython/all.py +3 -0
  60. sage/cpython/atexit.cp314-win_amd64.pyd +0 -0
  61. sage/cpython/atexit.pyx +269 -0
  62. sage/cpython/builtin_types.cp314-win_amd64.pyd +0 -0
  63. sage/cpython/builtin_types.pyx +7 -0
  64. sage/cpython/cython_metaclass.cp314-win_amd64.pyd +0 -0
  65. sage/cpython/cython_metaclass.h +117 -0
  66. sage/cpython/cython_metaclass.pxd +3 -0
  67. sage/cpython/cython_metaclass.pyx +130 -0
  68. sage/cpython/debug.cp314-win_amd64.pyd +0 -0
  69. sage/cpython/debug.pyx +302 -0
  70. sage/cpython/dict_del_by_value.cp314-win_amd64.pyd +0 -0
  71. sage/cpython/dict_del_by_value.pxd +9 -0
  72. sage/cpython/dict_del_by_value.pyx +191 -0
  73. sage/cpython/dict_internal.h +80 -0
  74. sage/cpython/getattr.cp314-win_amd64.pyd +0 -0
  75. sage/cpython/getattr.pxd +9 -0
  76. sage/cpython/getattr.pyx +439 -0
  77. sage/cpython/pycore_long.h +97 -0
  78. sage/cpython/pycore_long.pxd +10 -0
  79. sage/cpython/python_debug.h +44 -0
  80. sage/cpython/python_debug.pxd +47 -0
  81. sage/cpython/pyx_visit.h +13 -0
  82. sage/cpython/string.cp314-win_amd64.pyd +0 -0
  83. sage/cpython/string.pxd +76 -0
  84. sage/cpython/string.pyx +34 -0
  85. sage/cpython/string_impl.h +60 -0
  86. sage/cpython/type.cp314-win_amd64.pyd +0 -0
  87. sage/cpython/type.pxd +2 -0
  88. sage/cpython/type.pyx +40 -0
  89. sage/cpython/wrapperdescr.pxd +67 -0
  90. sage/ext/all__sagemath_objects.py +3 -0
  91. sage/ext/ccobject.h +64 -0
  92. sage/ext/cplusplus.pxd +17 -0
  93. sage/ext/mod_int.h +30 -0
  94. sage/ext/mod_int.pxd +24 -0
  95. sage/ext/stdsage.pxd +39 -0
  96. sage/groups/all__sagemath_objects.py +1 -0
  97. sage/groups/group.cp314-win_amd64.pyd +0 -0
  98. sage/groups/group.pxd +14 -0
  99. sage/groups/group.pyx +296 -0
  100. sage/groups/old.cp314-win_amd64.pyd +0 -0
  101. sage/groups/old.pxd +14 -0
  102. sage/groups/old.pyx +219 -0
  103. sage/libs/all__sagemath_objects.py +3 -0
  104. sage/libs/gmp/__init__.py +1 -0
  105. sage/libs/gmp/all.pxd +6 -0
  106. sage/libs/gmp/binop.pxd +23 -0
  107. sage/libs/gmp/misc.pxd +8 -0
  108. sage/libs/gmp/mpf.pxd +88 -0
  109. sage/libs/gmp/mpn.pxd +57 -0
  110. sage/libs/gmp/mpq.pxd +57 -0
  111. sage/libs/gmp/mpz.pxd +202 -0
  112. sage/libs/gmp/pylong.cp314-win_amd64.pyd +0 -0
  113. sage/libs/gmp/pylong.pxd +12 -0
  114. sage/libs/gmp/pylong.pyx +150 -0
  115. sage/libs/gmp/random.pxd +25 -0
  116. sage/libs/gmp/randomize.pxd +59 -0
  117. sage/libs/gmp/types.pxd +53 -0
  118. sage/libs/gmpxx.pxd +19 -0
  119. sage/misc/abstract_method.py +276 -0
  120. sage/misc/all__sagemath_objects.py +43 -0
  121. sage/misc/bindable_class.py +253 -0
  122. sage/misc/c3_controlled.cp314-win_amd64.pyd +0 -0
  123. sage/misc/c3_controlled.pxd +2 -0
  124. sage/misc/c3_controlled.pyx +1402 -0
  125. sage/misc/cachefunc.cp314-win_amd64.pyd +0 -0
  126. sage/misc/cachefunc.pxd +43 -0
  127. sage/misc/cachefunc.pyx +3801 -0
  128. sage/misc/call.py +188 -0
  129. sage/misc/classcall_metaclass.cp314-win_amd64.pyd +0 -0
  130. sage/misc/classcall_metaclass.pxd +14 -0
  131. sage/misc/classcall_metaclass.pyx +599 -0
  132. sage/misc/constant_function.cp314-win_amd64.pyd +0 -0
  133. sage/misc/constant_function.pyx +130 -0
  134. sage/misc/decorators.py +739 -0
  135. sage/misc/fast_methods.cp314-win_amd64.pyd +0 -0
  136. sage/misc/fast_methods.pxd +20 -0
  137. sage/misc/fast_methods.pyx +351 -0
  138. sage/misc/flatten.py +90 -0
  139. sage/misc/fpickle.cp314-win_amd64.pyd +0 -0
  140. sage/misc/fpickle.pyx +176 -0
  141. sage/misc/function_mangling.cp314-win_amd64.pyd +0 -0
  142. sage/misc/function_mangling.pxd +11 -0
  143. sage/misc/function_mangling.pyx +308 -0
  144. sage/misc/inherit_comparison.cp314-win_amd64.pyd +0 -0
  145. sage/misc/inherit_comparison.pxd +5 -0
  146. sage/misc/inherit_comparison.pyx +105 -0
  147. sage/misc/instancedoc.cp314-win_amd64.pyd +0 -0
  148. sage/misc/instancedoc.pyx +331 -0
  149. sage/misc/lazy_attribute.cp314-win_amd64.pyd +0 -0
  150. sage/misc/lazy_attribute.pyx +607 -0
  151. sage/misc/lazy_format.py +132 -0
  152. sage/misc/lazy_import.cp314-win_amd64.pyd +0 -0
  153. sage/misc/lazy_import.pxd +13 -0
  154. sage/misc/lazy_import.pyx +1307 -0
  155. sage/misc/lazy_import_cache.py +36 -0
  156. sage/misc/lazy_list.cp314-win_amd64.pyd +0 -0
  157. sage/misc/lazy_list.pxd +19 -0
  158. sage/misc/lazy_list.pyx +1187 -0
  159. sage/misc/lazy_string.cp314-win_amd64.pyd +0 -0
  160. sage/misc/lazy_string.pxd +7 -0
  161. sage/misc/lazy_string.pyx +546 -0
  162. sage/misc/misc.py +980 -0
  163. sage/misc/misc_c.cp314-win_amd64.pyd +0 -0
  164. sage/misc/misc_c.pxd +3 -0
  165. sage/misc/misc_c.pyx +765 -0
  166. sage/misc/namespace_package.py +37 -0
  167. sage/misc/nested_class.cp314-win_amd64.pyd +0 -0
  168. sage/misc/nested_class.pxd +3 -0
  169. sage/misc/nested_class.pyx +394 -0
  170. sage/misc/persist.cp314-win_amd64.pyd +0 -0
  171. sage/misc/persist.pyx +1279 -0
  172. sage/misc/prandom.py +418 -0
  173. sage/misc/randstate.cp314-win_amd64.pyd +0 -0
  174. sage/misc/randstate.pxd +31 -0
  175. sage/misc/randstate.pyx +1096 -0
  176. sage/misc/repr.py +203 -0
  177. sage/misc/reset.cp314-win_amd64.pyd +0 -0
  178. sage/misc/reset.pyx +196 -0
  179. sage/misc/sage_ostools.cp314-win_amd64.pyd +0 -0
  180. sage/misc/sage_ostools.pyx +323 -0
  181. sage/misc/sage_timeit.py +275 -0
  182. sage/misc/sage_timeit_class.cp314-win_amd64.pyd +0 -0
  183. sage/misc/sage_timeit_class.pyx +120 -0
  184. sage/misc/sage_unittest.py +639 -0
  185. sage/misc/sageinspect.py +2792 -0
  186. sage/misc/session.cp314-win_amd64.pyd +0 -0
  187. sage/misc/session.pyx +392 -0
  188. sage/misc/superseded.py +576 -0
  189. sage/misc/test_nested_class.py +228 -0
  190. sage/misc/timing.py +264 -0
  191. sage/misc/unknown.py +222 -0
  192. sage/misc/verbose.py +253 -0
  193. sage/misc/weak_dict.cp314-win_amd64.pyd +0 -0
  194. sage/misc/weak_dict.pxd +15 -0
  195. sage/misc/weak_dict.pyx +1197 -0
  196. sage/modules/all__sagemath_objects.py +1 -0
  197. sage/modules/module.cp314-win_amd64.pyd +0 -0
  198. sage/modules/module.pxd +5 -0
  199. sage/modules/module.pyx +329 -0
  200. sage/rings/all__sagemath_objects.py +3 -0
  201. sage/rings/integer_fake.h +22 -0
  202. sage/rings/integer_fake.pxd +55 -0
  203. sage/rings/integer_fake.pyi +8 -0
  204. sage/sets/all__sagemath_objects.py +3 -0
  205. sage/sets/pythonclass.cp314-win_amd64.pyd +0 -0
  206. sage/sets/pythonclass.pxd +9 -0
  207. sage/sets/pythonclass.pyx +247 -0
  208. sage/structure/__init__.py +13 -0
  209. sage/structure/all.py +30 -0
  210. sage/structure/category_object.cp314-win_amd64.pyd +0 -0
  211. sage/structure/category_object.pxd +28 -0
  212. sage/structure/category_object.pyx +1090 -0
  213. sage/structure/coerce.cp314-win_amd64.pyd +0 -0
  214. sage/structure/coerce.pxd +44 -0
  215. sage/structure/coerce.pyx +2113 -0
  216. sage/structure/coerce_actions.cp314-win_amd64.pyd +0 -0
  217. sage/structure/coerce_actions.pxd +27 -0
  218. sage/structure/coerce_actions.pyx +988 -0
  219. sage/structure/coerce_dict.cp314-win_amd64.pyd +0 -0
  220. sage/structure/coerce_dict.pxd +51 -0
  221. sage/structure/coerce_dict.pyx +1557 -0
  222. sage/structure/coerce_exceptions.py +23 -0
  223. sage/structure/coerce_maps.cp314-win_amd64.pyd +0 -0
  224. sage/structure/coerce_maps.pxd +24 -0
  225. sage/structure/coerce_maps.pyx +656 -0
  226. sage/structure/debug_options.cp314-win_amd64.pyd +0 -0
  227. sage/structure/debug_options.pxd +6 -0
  228. sage/structure/debug_options.pyx +54 -0
  229. sage/structure/dynamic_class.py +541 -0
  230. sage/structure/element.cp314-win_amd64.pyd +0 -0
  231. sage/structure/element.pxd +271 -0
  232. sage/structure/element.pyx +4584 -0
  233. sage/structure/element_wrapper.cp314-win_amd64.pyd +0 -0
  234. sage/structure/element_wrapper.pxd +12 -0
  235. sage/structure/element_wrapper.pyx +582 -0
  236. sage/structure/factorization.py +1457 -0
  237. sage/structure/factorization_integer.py +154 -0
  238. sage/structure/factory.cp314-win_amd64.pyd +0 -0
  239. sage/structure/factory.pyx +863 -0
  240. sage/structure/formal_sum.py +489 -0
  241. sage/structure/gens_py.py +73 -0
  242. sage/structure/global_options.py +1725 -0
  243. sage/structure/indexed_generators.py +863 -0
  244. sage/structure/list_clone.cp314-win_amd64.pyd +0 -0
  245. sage/structure/list_clone.pxd +65 -0
  246. sage/structure/list_clone.pyx +1867 -0
  247. sage/structure/list_clone_demo.cp314-win_amd64.pyd +0 -0
  248. sage/structure/list_clone_demo.pyx +248 -0
  249. sage/structure/list_clone_timings.py +179 -0
  250. sage/structure/list_clone_timings_cy.cp314-win_amd64.pyd +0 -0
  251. sage/structure/list_clone_timings_cy.pyx +86 -0
  252. sage/structure/mutability.cp314-win_amd64.pyd +0 -0
  253. sage/structure/mutability.pxd +21 -0
  254. sage/structure/mutability.pyx +346 -0
  255. sage/structure/nonexact.py +69 -0
  256. sage/structure/parent.cp314-win_amd64.pyd +0 -0
  257. sage/structure/parent.pxd +112 -0
  258. sage/structure/parent.pyx +3087 -0
  259. sage/structure/parent_base.cp314-win_amd64.pyd +0 -0
  260. sage/structure/parent_base.pxd +13 -0
  261. sage/structure/parent_base.pyx +35 -0
  262. sage/structure/parent_gens.cp314-win_amd64.pyd +0 -0
  263. sage/structure/parent_gens.pxd +22 -0
  264. sage/structure/parent_gens.pyx +374 -0
  265. sage/structure/parent_old.cp314-win_amd64.pyd +0 -0
  266. sage/structure/parent_old.pxd +24 -0
  267. sage/structure/parent_old.pyx +278 -0
  268. sage/structure/proof/__init__.py +1 -0
  269. sage/structure/proof/all.py +243 -0
  270. sage/structure/proof/proof.py +300 -0
  271. sage/structure/richcmp.cp314-win_amd64.pyd +0 -0
  272. sage/structure/richcmp.pxd +212 -0
  273. sage/structure/richcmp.pyx +494 -0
  274. sage/structure/sage_object.cp314-win_amd64.pyd +0 -0
  275. sage/structure/sage_object.pxd +3 -0
  276. sage/structure/sage_object.pyx +1088 -0
  277. sage/structure/sage_object_test.py +19 -0
  278. sage/structure/sequence.py +937 -0
  279. sage/structure/set_factories.py +1178 -0
  280. sage/structure/set_factories_example.py +527 -0
  281. sage/structure/support_view.py +164 -0
  282. sage/structure/test_factory.py +56 -0
  283. sage/structure/unique_representation.py +1443 -0
@@ -0,0 +1,1725 @@
1
+ # sage_setup: distribution = sagemath-objects
2
+ r"""
3
+ Global options
4
+
5
+ The :class:`GlobalOptions` class provides a generic mechanism for
6
+ setting and accessing **global** options for parents in one or several
7
+ related classes, typically for customizing the representation of their
8
+ elements. This class will eventually also support setting options on a
9
+ parent by parent basis.
10
+
11
+ These options should be "attached" to one or more classes as an options method.
12
+
13
+ .. SEEALSO::
14
+
15
+ For good examples of :class:`GlobalOptions` in action see
16
+ :obj:`sage.combinat.partition.Partitions.options` and
17
+ :obj:`sage.combinat.tableau.Tableaux.options`.
18
+
19
+ .. _construction_section:
20
+
21
+ Construction of options classes
22
+ -------------------------------
23
+
24
+ The general setup for creating a set of global options is::
25
+
26
+ sage: from sage.structure.global_options import GlobalOptions
27
+ sage: class MyOptions(GlobalOptions):
28
+ ....: '''
29
+ ....: Nice options
30
+ ....:
31
+ ....: @OPTIONS@
32
+ ....: '''
33
+ ....: NAME = 'option name'
34
+ ....: module = 'sage.some_module.some_file'
35
+ ....: option_class = 'name_of_class_controlled_by_options'
36
+ ....: first_option = dict(default='with_bells',
37
+ ....: description='Changes the functionality of _repr_',
38
+ ....: values=dict(with_bells='causes _repr_ to print with bells',
39
+ ....: with_whistles='causes _repr_ to print with whistles'),
40
+ ....: alias=dict(bells='option1', whistles='option2'))
41
+ ....: # second_option = dict(...)
42
+ ....: # third_option = dict(...)
43
+
44
+ Note the syntax using the ``class`` keyword. However, because of some
45
+ metaclass magic, the resulting ``MyOptions`` object becomes an instance
46
+ of ``GlobalOptions`` instead of a subclass. So, despite the ``class``
47
+ syntax, ``MyOptions`` is not a class.
48
+
49
+ The options constructed by :class:`GlobalOptions` have to be explicitly
50
+ associated to the class that they control using the following arguments:
51
+
52
+ - ``NAME`` -- a descriptive name for the options class; this is
53
+ optional. The default is the name of the constructed class.
54
+
55
+ - ``module`` -- the sage module containing the options class (optional)
56
+
57
+ - ``option_class`` -- the name of the options class; this is optional and
58
+ defaults to ``NAME`` if not explicitly set
59
+
60
+ It is only possible to pickle a :class:`GlobalOptions` class if the
61
+ corresponding module is specified *and* if the options are explicitly
62
+ attached to the corresponding class as a *options* method.
63
+
64
+ Each option is specified as a dictionary which describes the possible
65
+ values for the option and its documentation. The possible entries in this
66
+ dictionary are:
67
+
68
+ - ``alias`` -- allows for several option values to do the same thing
69
+
70
+ - ``alt_name`` -- an alternative name for this option
71
+
72
+ - ``checker`` -- a validation function which returns whether a user
73
+ supplied value is valid or not. This is typically useful for large
74
+ lists of legal values such as :class:`~sage.rings.semirings.non_negative_integer_semiring.NN`.
75
+
76
+ - ``default`` -- gives the default value for the option
77
+
78
+ - ``description`` -- a one line description of the option
79
+
80
+ - ``link_to`` -- links this option to another one in another set of
81
+ global options. This is used for example to allow
82
+ :class:`Partitions` and :class:`Tableaux` to share the same
83
+ ``convention`` option.
84
+
85
+ - ``setter`` -- a function which is called **after** the value of the
86
+ option is changed
87
+
88
+ - ``values`` -- dictionary assigning each valid value for the option
89
+ to a short description of what it does
90
+
91
+ - ``case_sensitive`` -- boolean (default: ``True``); depending on
92
+ whether the values of the option are case sensitive
93
+
94
+ For each option, either a complete list of possible values, via ``values``, or a
95
+ validation function, via ``checker``, must be given. The values can be quite
96
+ arbitrary, including user-defined functions which customize the default
97
+ behaviour of the classes such as the output of ``_repr_`` or :func:`latex`. See
98
+ :ref:`dispatcher` below, and :meth:`~GlobalOptions._dispatcher`, for more
99
+ information.
100
+
101
+ The documentation for the options is automatically constructed from
102
+ the docstring of the class by replacing the magic word ``@OPTIONS@``
103
+ with a description of each option.
104
+
105
+ The basic structure for defining a :class:`GlobalOptions` class is best
106
+ illustrated by an example::
107
+
108
+ sage: from sage.structure.global_options import GlobalOptions
109
+ sage: class Menu():
110
+ ....: class options(GlobalOptions):
111
+ ....: '''
112
+ ....: Fancy documentation
113
+ ....: -------------------
114
+ ....:
115
+ ....: @OPTIONS@
116
+ ....:
117
+ ....: The END!
118
+ ....: '''
119
+ ....: NAME = 'menu'
120
+ ....: entree = dict(default='soup',
121
+ ....: description='The first course of a meal',
122
+ ....: values=dict(soup='soup of the day', bread='oven baked'),
123
+ ....: alias=dict(rye='bread'))
124
+ ....: appetizer = dict(alt_name='entree')
125
+ ....: main = dict(default='pizza', description='Main meal',
126
+ ....: values=dict(pizza='thick crust', pasta='penne arrabiata'),
127
+ ....: case_sensitive=False)
128
+ ....: dessert = dict(default='espresso', description='Dessert',
129
+ ....: values=dict(espresso='life begins again',
130
+ ....: cake='waist begins again',
131
+ ....: cream='fluffy, white stuff'))
132
+ ....: tip = dict(default=10, description='Reward for good service',
133
+ ....: checker = lambda tip: tip in range(20))
134
+ sage: Menu.options
135
+ Current options for menu
136
+ - dessert: espresso
137
+ - entree: soup
138
+ - main: pizza
139
+ - tip: 10
140
+
141
+ In the examples above, the options are constructed when the ``options``
142
+ object is created. However, it is also possible to construct the options
143
+ dynamically using the :meth:`GlobalOptions._add_to_options` methods.
144
+
145
+ For more details see :class:`GlobalOptions`.
146
+
147
+ Accessing and setting option values
148
+ -----------------------------------
149
+
150
+ All options and their values, when they are strings, are forced to be lower
151
+ case. The values of an options class can be set and accessed by calling the
152
+ class or by treating the class as an array.
153
+
154
+ Continuing the example from :ref:`construction_section`::
155
+
156
+ sage: Menu.options
157
+ Current options for menu
158
+ - dessert: espresso
159
+ - entree: soup
160
+ - main: pizza
161
+ - tip: 10
162
+ sage: Menu.options.dessert
163
+ espresso
164
+ sage: Menu.options.dessert = 'cake'
165
+ sage: Menu.options.dessert
166
+ cake
167
+
168
+ Note that, provided there is no ambiguity, options and their values can be
169
+ abbreviated::
170
+
171
+ sage: Menu.options('d')
172
+ 'cake'
173
+ sage: Menu.options('m','t',des='esp', ent='sou') # get and set several values at once
174
+ ['pizza', 10]
175
+ sage: Menu.options(t=15)
176
+ sage: Menu.options('tip')
177
+ 15
178
+ sage: Menu.options.tip
179
+ 15
180
+ sage: Menu.options(e='s', m='Pi'); Menu.options()
181
+ Current options for menu
182
+ - dessert: cake
183
+ - entree: soup
184
+ - main: pizza
185
+ - tip: 15
186
+ sage: Menu.options(m='P')
187
+ Traceback (most recent call last):
188
+ ...
189
+ ValueError: P is not a valid value for main in the options for menu
190
+
191
+
192
+ Setter functions
193
+ ----------------
194
+
195
+ Each option of a :class:`GlobalOptions` can be equipped with an optional setter
196
+ function which is called **after** the value of the option is changed. In the
197
+ following example, setting the option 'add' changes the state of the class by
198
+ setting an attribute in this class using a :func:`classmethod`. Note that the
199
+ options object is inserted after the creation of the class in order to access
200
+ the :func:`classmethod` as ``A.setter``::
201
+
202
+ sage: from sage.structure.global_options import GlobalOptions
203
+ sage: class A(SageObject):
204
+ ....: state = 0
205
+ ....: @classmethod
206
+ ....: def setter(cls, option, val):
207
+ ....: cls.state += int(val)
208
+ sage: class options(GlobalOptions):
209
+ ....: NAME = "A"
210
+ ....: add = dict(default=1,
211
+ ....: checker=lambda v: int(v)>0,
212
+ ....: description='An option with a setter',
213
+ ....: setter=A.setter)
214
+ sage: A.options = options
215
+ sage: A.options
216
+ Current options for A
217
+ - add: 1
218
+ sage: a = A(); a.state
219
+ 1
220
+ sage: a.options()
221
+ Current options for A
222
+ - add: 1
223
+ sage: a.options(add=4)
224
+ sage: a.state
225
+ 5
226
+ sage: a.options()
227
+ Current options for A
228
+ - add: 4
229
+
230
+ Documentation for options
231
+ -------------------------
232
+
233
+ The documentation for a :class:`GlobalOptions` is automatically generated from
234
+ the supplied options. For example, the generated documentation for the options
235
+ ``menu`` defined in :ref:`construction_section` is the following:
236
+
237
+ .. CODE-BLOCK:: text
238
+
239
+ Fancy documentation
240
+ -------------------
241
+
242
+ OPTIONS:
243
+
244
+ - ``appetizer`` -- alternative name for ``entree``
245
+ - ``dessert`` -- (default: ``espresso``)
246
+ Dessert
247
+
248
+ - ``cake`` -- waist begins again
249
+ - ``cream`` -- fluffy, white stuff
250
+ - ``espresso`` -- life begins again
251
+
252
+ - ``entree`` -- (default: ``soup``)
253
+ The first course of a meal
254
+
255
+ - ``bread`` -- oven baked
256
+ - ``rye`` -- alias for ``bread``
257
+ - ``soup`` -- soup of the day
258
+
259
+ - ``main`` -- (default: ``pizza``)
260
+ Main meal
261
+
262
+ - ``pasta`` -- penne arrabiata
263
+ - ``pizza`` -- thick crust
264
+
265
+ - ``tip`` -- (default: ``10``)
266
+ Reward for good service
267
+
268
+
269
+ The END!
270
+
271
+ See :class:`~sage.structure.global_options.GlobalOptions` for more features of these options.
272
+
273
+ In addition, help on each option, and its list of possible values, can be
274
+ obtained by (trying to) set the option equal to '?'::
275
+
276
+ sage: Menu.options.dessert? # not tested
277
+ - ``dessert`` -- (default: ``espresso``)
278
+ Dessert
279
+
280
+ - ``cake`` -- waist begins again
281
+ - ``cream`` -- fluffy, white stuff
282
+ - ``espresso`` -- life begins again
283
+
284
+ .. _dispatcher:
285
+
286
+ Dispatchers
287
+ -----------
288
+
289
+ The whole idea of a :class:`GlobalOptions` class is that the options change the
290
+ default behaviour of the associated classes. This can be done either by simply
291
+ checking what the current value of the relevant option is. Another possibility
292
+ is to use the options class as a dispatcher to associated methods. To use the
293
+ dispatcher feature of a :class:`GlobalOptions` class it is necessary to implement
294
+ separate methods for each value of the option where the naming convention for
295
+ these methods is that they start with a common prefix and finish with the value
296
+ of the option.
297
+
298
+ If the value of a dispatchable option is set equal to a (user defined) function
299
+ then this function is called instead of a class method.
300
+
301
+ For example, the options ``MyOptions`` can be used to dispatch the ``_repr_``
302
+ method of the associated class ``MyClass`` as follows:
303
+
304
+ .. CODE-BLOCK:: python
305
+
306
+ class MyClass(...):
307
+ def _repr_(self):
308
+ return self.options._dispatch(self,'_repr_','first_option')
309
+ def _repr_with_bells(self):
310
+ print('Bell!')
311
+ def _repr_with_whistles(self):
312
+ print('Whistles!')
313
+ class MyOptions(GlobalOptions):
314
+ ...
315
+
316
+ In this example, ``first_option`` is an option of ``MyOptions`` which takes
317
+ values ``bells``, ``whistles``, and so on. Note that it is necessary to make
318
+ ``self``, which is an instance of ``MyClass``, an argument of the dispatcher
319
+ because :meth:`~GlobalOptions._dispatch()` is a method of :class:`GlobalOptions`
320
+ and not a method of ``MyClass``. Apart from ``MyOptions``, as it is a method of
321
+ this class, the arguments are the attached class (here ``MyClass``), the prefix
322
+ of the method of ``MyClass`` being dispatched, the option of ``MyOptions``
323
+ which controls the dispatching. All other arguments are passed through to the
324
+ corresponding methods of ``MyClass``. In general, a dispatcher is invoked as:
325
+
326
+ .. CODE-BLOCK:: python
327
+
328
+ self.options._dispatch(self, dispatch_to, option, *args, **kargs)
329
+
330
+ Usually this will result in the method
331
+ ``dispatch_to + '_' + MyOptions(options)`` of ``self`` being called with
332
+ arguments ``*args`` and ``**kargs`` (if ``dispatch_to[-1] == '_'`` then the
333
+ method ``dispatch_to + MyOptions(options)`` is called).
334
+
335
+ If ``MyOptions(options)`` is itself a function then the dispatcher will call
336
+ this function instead. In this way, it is possible to allow the user to
337
+ customise the default behaviour of this method. See
338
+ :meth:`~GlobalOptions._dispatch` for an example of how this can be achieved.
339
+
340
+ The dispatching capabilities of :class:`GlobalOptions` allows options to be
341
+ applied automatically without needing to parse different values of the option
342
+ (the cost is that there must be a method for each value). The dispatching
343
+ capabilities can also be used to make one option control several methods:
344
+
345
+ .. CODE-BLOCK:: python
346
+
347
+ def __le__(self, other):
348
+ return self.options._dispatch(self, '_le_','cmp', other)
349
+ def __ge__(self, other):
350
+ return self.options._dispatch(self, '_ge_','cmp', other)
351
+ def _le_option_a(self, other):
352
+ return ...
353
+ def _ge_option_a(self, other):
354
+ return ...
355
+ def _le_option_b(self, other):
356
+ return ...
357
+ def _ge_option_b(self, other):
358
+ return ...
359
+
360
+ See :meth:`~GlobalOptions._dispatch` for more details.
361
+
362
+ Doc testing
363
+ -----------
364
+
365
+ All of the options and their effects should be doc-tested. However, in order
366
+ not to break other tests, all options should be returned to their default state
367
+ at the end of each test. To make this easier, every :class:`GlobalOptions` class has
368
+ a :meth:`~GlobalOptions._reset()` method for doing exactly this.
369
+
370
+
371
+ Pickling
372
+ --------
373
+
374
+ Options classes can only be pickled if they are the options for some standard
375
+ sage class. In this case the class is specified using the arguments to
376
+ :class:`GlobalOptions`. For example
377
+ :meth:`~sage.combinat.partition.Partitions.options` is defined as:
378
+
379
+ .. CODE-BLOCK:: python
380
+
381
+ class Partitions(UniqueRepresentation, Parent):
382
+ ...
383
+ class options(GlobalOptions):
384
+ NAME = 'Partitions'
385
+ module = 'sage.combinat.partition'
386
+ ...
387
+
388
+ Here is an example to test the pickling of a :class:`GlobalOptions` instance::
389
+
390
+ sage: TestSuite(Partitions.options).run()
391
+
392
+ TESTS:
393
+
394
+ Check that the old call syntax still works::
395
+
396
+ sage: class Menu():
397
+ ....: options = GlobalOptions('menu',
398
+ ....: doc='Fancy documentation\n'+'-'*19, end_doc='The END!',
399
+ ....: entree=dict(default='soup',
400
+ ....: description='The first course of a meal',
401
+ ....: values=dict(soup='soup of the day', bread='oven baked'),
402
+ ....: alias=dict(rye='bread')),
403
+ ....: appetizer=dict(alt_name='entree'),
404
+ ....: main=dict(default='pizza', description='Main meal',
405
+ ....: values=dict(pizza='thick crust', pasta='penne arrabiata'),
406
+ ....: case_sensitive=False),
407
+ ....: dessert=dict(default='espresso', description='Dessert',
408
+ ....: values=dict(espresso='life begins again',
409
+ ....: cake='waist begins again',
410
+ ....: cream='fluffy, white stuff')),
411
+ ....: tip=dict(default=10, description='Reward for good service',
412
+ ....: checker=lambda tip: tip in range(20))
413
+ ....: )
414
+ sage: Menu.options
415
+ Current options for menu
416
+ - dessert: espresso
417
+ - entree: soup
418
+ - main: pizza
419
+ - tip: 10
420
+
421
+ We can have a ``name`` option::
422
+
423
+ sage: class MyOptions(GlobalOptions):
424
+ ....: name = dict(default='alice', values={'alice': "A", 'bob': "B"})
425
+ sage: MyOptions
426
+ Current options for MyOptions
427
+ - name: alice
428
+
429
+ Check that the ``name`` and ``NAME`` keywords are both supported with
430
+ this syntax::
431
+
432
+ sage: GlobalOptions(name='menu')
433
+ Current options for menu
434
+ sage: GlobalOptions(NAME='menu')
435
+ Current options for menu
436
+ sage: GlobalOptions()
437
+ Traceback (most recent call last):
438
+ ...
439
+ TypeError: GlobalOptions() is missing keyword argument 'name'
440
+
441
+ Test the documentation examples above::
442
+
443
+ sage: print(Menu.options.__doc__)
444
+ Fancy documentation
445
+ -------------------
446
+ <BLANKLINE>
447
+ OPTIONS:
448
+ <BLANKLINE>
449
+ - ``appetizer`` -- alternative name for ``entree``
450
+ - ``dessert`` -- (default: ``espresso``)
451
+ Dessert
452
+ <BLANKLINE>
453
+ - ``cake`` -- waist begins again
454
+ - ``cream`` -- fluffy, white stuff
455
+ - ``espresso`` -- life begins again
456
+ <BLANKLINE>
457
+ - ``entree`` -- (default: ``soup``)
458
+ The first course of a meal
459
+ <BLANKLINE>
460
+ - ``bread`` -- oven baked
461
+ - ``rye`` -- alias for ``bread``
462
+ - ``soup`` -- soup of the day
463
+ <BLANKLINE>
464
+ - ``main`` -- (default: ``pizza``)
465
+ Main meal
466
+ <BLANKLINE>
467
+ - ``pasta`` -- penne arrabiata
468
+ - ``pizza`` -- thick crust
469
+ <BLANKLINE>
470
+ - ``tip`` -- (default: ``10``)
471
+ Reward for good service
472
+ <BLANKLINE>
473
+ <BLANKLINE>
474
+ <BLANKLINE>
475
+ <BLANKLINE>
476
+ The END!
477
+ See :class:`~sage.structure.global_options.GlobalOptions` for more features of these options.
478
+
479
+ ::
480
+
481
+ sage: print(Menu.options.dessert.__doc__)
482
+ - ``dessert`` -- (default: ``espresso``)
483
+ Dessert
484
+ <BLANKLINE>
485
+ - ``cake`` -- waist begins again
486
+ - ``cream`` -- fluffy, white stuff
487
+ - ``espresso`` -- life begins again
488
+ <BLANKLINE>
489
+
490
+ AUTHORS:
491
+
492
+ - Andrew Mathas (2013): initial version
493
+ - Andrew Mathas (2016): overhaul making the options attributes, enabling
494
+ pickling and attaching the options to a class.
495
+ - Jeroen Demeyer (2017): use subclassing to create instances
496
+ """
497
+
498
+ # ****************************************************************************
499
+ # Copyright (C) 2013,2016 Andrew Mathas <andrew dot mathas at sydney dot edu dot au>
500
+ # Copyright (C) 2017 Jeroen Demeyer <J.Demeyer@UGent.be>
501
+ #
502
+ # This program is free software: you can redistribute it and/or modify
503
+ # it under the terms of the GNU General Public License as published by
504
+ # the Free Software Foundation, either version 2 of the License, or
505
+ # (at your option) any later version.
506
+ # https://www.gnu.org/licenses/
507
+ # ****************************************************************************
508
+
509
+
510
+ from importlib import import_module
511
+ from pickle import PicklingError
512
+ from textwrap import dedent
513
+
514
+ from sage.misc.instancedoc import instancedoc
515
+
516
+
517
+ class Option:
518
+ r"""
519
+ An option.
520
+
521
+ Each option for an options class is an instance of this class which
522
+ implements the magic that allows the options to the attributes of the
523
+ options class that can be looked up, set and called.
524
+
525
+ By way of example, this class implements the following functionality.
526
+
527
+ EXAMPLES::
528
+
529
+ sage: # needs sage.combinat
530
+ sage: Partitions.options.display
531
+ list
532
+ sage: Partitions.options.display = 'compact'
533
+ sage: Partitions.options.display('list')
534
+ sage: Partitions.options._reset()
535
+
536
+ TESTS::
537
+
538
+ sage: TestSuite(Partitions.options.display).run()
539
+ """
540
+ __name__ = 'Option class'
541
+
542
+ def __init__(self, options, name):
543
+ r"""
544
+ Initialise an option by settings its ``name``, "parent" option class
545
+ ``options`` and doc-string.
546
+
547
+ EXAMPLES::
548
+
549
+ sage: type(Partitions.options.display) # indirect doctest
550
+ <class 'sage.structure.global_options.Option'>
551
+ """
552
+ self._name = name
553
+ self._options = options
554
+ self.__doc__ = options._doc[name]
555
+ super().__init__()
556
+
557
+ def __repr__(self):
558
+ r"""
559
+ Return a string representation for this collection of options.
560
+
561
+ EXAMPLES::
562
+
563
+ sage: Partitions.options.display # indirect doctest
564
+ list
565
+ """
566
+ # NOTE: we intentionally use str() instead of repr()
567
+ return str(self._options[self._name])
568
+
569
+ def __add__(self, other):
570
+ r"""
571
+ Return the object obtained by adding ``self`` and ``other``, where
572
+ ``self`` behaves like its value.
573
+
574
+ EXAMPLES::
575
+
576
+ sage: Tableaux.options.convention + ' is good' # needs sage.combinat
577
+ 'English is good'
578
+ """
579
+ return self._options[self._name] + other
580
+
581
+ def __radd__(self, other):
582
+ r"""
583
+ Return the object obtained by adding ``other`` and ``self``, where
584
+ ``self`` behaves like its value.
585
+
586
+ EXAMPLES::
587
+
588
+ sage: 'Good ' + Tableaux.options.convention # needs sage.combinat
589
+ 'Good English'
590
+ """
591
+ return other + self._options[self._name]
592
+
593
+ def __mul__(self, other):
594
+ r"""
595
+ Return the object obtained by adding ``self`` and ``other``, where
596
+ ``self`` behaves like its value.
597
+
598
+ EXAMPLES::
599
+
600
+ sage: Tableaux.options.convention + ' is good' # needs sage.combinat
601
+ 'English is good'
602
+ """
603
+ return self._options[self._name] * other
604
+
605
+ def __rmul__(self, other):
606
+ r"""
607
+ Return the object obtained by r-adding ``other`` and ``self``, where
608
+ ``self`` behaves like its value.
609
+
610
+ EXAMPLES::
611
+
612
+ sage: 'Good ' + Tableaux.options.convention # needs sage.combinat
613
+ 'Good English'
614
+ """
615
+ return other * self._options[self._name]
616
+
617
+ def __bool__(self) -> bool:
618
+ r"""
619
+ Return the value of this option interpreted as a boolean.
620
+
621
+ EXAMPLES::
622
+
623
+ sage: # needs sage.combinat sage.graphs sage.modules
624
+ sage: RiggedConfigurations.options.half_width_boxes_type_B
625
+ True
626
+ sage: 'yes' if RiggedConfigurations.options.half_width_boxes_type_B else 'no'
627
+ 'yes'
628
+ sage: RiggedConfigurations.options.half_width_boxes_type_B = False
629
+ sage: 'yes' if RiggedConfigurations.options.half_width_boxes_type_B else 'no'
630
+ 'no'
631
+ sage: RiggedConfigurations.options._reset()
632
+ """
633
+ return bool(self._options[self._name])
634
+
635
+ def __call__(self, *args):
636
+ r"""
637
+ Get or set value of the option ``self``.
638
+
639
+ EXAMPLES::
640
+
641
+ sage: # needs sage.combinat
642
+ sage: Partitions.options.display() # indirect doctest
643
+ 'list'
644
+ sage: Partitions.options.display('exp') # indirect doctest
645
+ sage: Partitions.options.display() # indirect doctest
646
+ 'exp_low'
647
+ sage: Partitions.options._reset()
648
+
649
+ TESTS:
650
+
651
+ Check that values can be set to ``None`` (:issue:`30763`)::
652
+
653
+ sage: from sage.structure.global_options import GlobalOptions
654
+ sage: class config(GlobalOptions):
655
+ ....: size = dict(default=42,
656
+ ....: description='integer or None',
657
+ ....: checker=lambda val: val is None or val >= 0)
658
+ sage: config.size()
659
+ 42
660
+ sage: config.size(None)
661
+ sage: config.size() is None
662
+ True
663
+ sage: config._reset()
664
+
665
+ Check the input::
666
+
667
+ sage: config.size(1, 2)
668
+ Traceback (most recent call last):
669
+ ...
670
+ TypeError: option takes at most one argument
671
+ """
672
+ if not args:
673
+ return self._options[self._name]
674
+ if len(args) > 1:
675
+ raise TypeError('option takes at most one argument')
676
+ self._options[self._name] = args[0]
677
+
678
+ def __eq__(self, other) -> bool:
679
+ r"""
680
+ Equality testing for an option in based on the value of the attribute.
681
+
682
+ EXAMPLES::
683
+
684
+ sage: Tableaux.options.convention # needs sage.combinat
685
+ English
686
+ sage: Tableaux.options.convention == "English" # needs sage.combinat
687
+ True
688
+ sage: Tableaux.options.convention == "French" # needs sage.combinat
689
+ False
690
+ """
691
+ return self._options[self._name] == other
692
+
693
+ def __ne__(self, other) -> bool:
694
+ r"""
695
+ Inequality testing for an option in based on the value of
696
+ the attribute.
697
+
698
+ EXAMPLES::
699
+
700
+ sage: Tableaux.options.convention # needs sage.combinat
701
+ English
702
+ sage: Tableaux.options.convention != "English" # needs sage.combinat
703
+ False
704
+ sage: Tableaux.options.convention != "French" # needs sage.combinat
705
+ True
706
+ """
707
+ return self._options[self._name] != other
708
+
709
+ def __hash__(self) -> int:
710
+ r"""
711
+ Return the hash of ``self``, which is the hash of the corresponding
712
+ value.
713
+
714
+ EXAMPLES::
715
+
716
+ sage: hash(Tableaux.options.convention) == hash(Tableaux.options('convention')) # needs sage.combinat
717
+ True
718
+ """
719
+ return hash(self._options[self._name])
720
+
721
+ def __str__(self) -> str:
722
+ r"""
723
+ Return the string representation of ``self``, which is the string of
724
+ the corresponding value.
725
+
726
+ EXAMPLES::
727
+
728
+ sage: str(Tableaux.options.convention) # needs sage.combinat
729
+ 'English'
730
+ """
731
+ return str(self._options[self._name])
732
+
733
+
734
+ class GlobalOptionsMetaMeta(type):
735
+ def __call__(self, name, bases, dict):
736
+ """
737
+ Called when subclassing an instance of ``self``.
738
+
739
+ Python translates ``class C(B): ...`` to
740
+ ``meta = type(B); C = meta("C", (B,), ...)``.
741
+ If we want to intercept this call ``meta(...)``, we need to
742
+ customize ``__call__`` in the metaclass of ``meta``, which is
743
+ this metametaclass.
744
+
745
+ EXAMPLES::
746
+
747
+ sage: from sage.structure.global_options import GlobalOptions
748
+ sage: type(GlobalOptions)
749
+ <class 'sage.structure.global_options.GlobalOptionsMeta'>
750
+ sage: type(type(GlobalOptions))
751
+ <class 'sage.structure.global_options.GlobalOptionsMetaMeta'>
752
+ sage: class G(GlobalOptions): pass
753
+ sage: type(G)
754
+ <class 'sage.structure.global_options.GlobalOptions'>
755
+
756
+ Since ``G`` is constructed using ``class`` syntax, the object
757
+ gets a ``__module__`` attribute, different from the
758
+ ``__module__`` attribute of its type (:class:`GlobalOptions`)::
759
+
760
+ sage: G.__module__
761
+ '__main__'
762
+ sage: type(G).__module__
763
+ 'sage.structure.global_options'
764
+
765
+ Multiple base classes are not allowed::
766
+
767
+ sage: class G(GlobalOptions, object): pass
768
+ Traceback (most recent call last):
769
+ ...
770
+ TypeError: GlobalOptions must be the only base class
771
+ """
772
+ # Allow only a single base class (which is GlobalOptions in
773
+ # practice).
774
+ # If we ever find a reasonable meaning for multiple base
775
+ # classes, note that Python 2 and Python 3 have different
776
+ # semantics for determining the metaclass when multiple base
777
+ # classes are involved.
778
+ #
779
+ # Note: On Python 3 bases is empty if the class was declared
780
+ # without any explicted bases:
781
+ if not bases:
782
+ bases = (object,)
783
+
784
+ if len(bases) != 1:
785
+ raise TypeError("GlobalOptions must be the only base class")
786
+
787
+ base = bases[0]
788
+ if not isinstance(base, self):
789
+ # For the creation of the initial GlobalOptions class, fall
790
+ # back to the usual class creation
791
+ return self.__new__(self, name, bases, dict)
792
+
793
+ # Create an instance of the base class (as opposed to an
794
+ # instance of self, which would be typical for a metaclass)
795
+ instance = base.__new__(base)
796
+
797
+ # Split dict in options for instance.__init__ and attributes to
798
+ # insert in the class __dict__
799
+ kwds = {"NAME": name}
800
+ for key, value in dict.items():
801
+ if key.startswith("__"):
802
+ instance.__dict__[key] = value
803
+ else:
804
+ kwds[key] = value
805
+
806
+ instance.__init__(**kwds)
807
+ return instance
808
+
809
+
810
+ class GlobalOptionsMeta(type, metaclass=GlobalOptionsMetaMeta):
811
+ """
812
+ Metaclass for :class:`GlobalOptions`.
813
+
814
+ This class is itself an instance of :class:`GlobalOptionsMetaMeta`,
815
+ which implements the subclass magic.
816
+ """
817
+
818
+
819
+ @instancedoc
820
+ class GlobalOptions(metaclass=GlobalOptionsMeta):
821
+ r"""
822
+ The :class:`GlobalOptions` class is a generic class for setting and
823
+ accessing global options for Sage objects.
824
+
825
+ While it is possible to create instances of :class:`GlobalOptions`
826
+ the usual way, the recommended syntax is to subclass from
827
+ ``GlobalOptions``. Thanks to some metaclass magic, this actually
828
+ creates an instance of ``GlobalOptions`` instead of a subclass.
829
+
830
+ INPUT (as "attributes" of the class):
831
+
832
+ - ``NAME`` -- specifies a name for the options class (optional;
833
+ default: class name)
834
+
835
+ - ``module`` -- gives the module that contains the associated options class
836
+
837
+ - ``option_class`` -- gives the name of the associated module class
838
+ (default: ``NAME``)
839
+
840
+ - option = ``dict(...)`` -- dictionary specifying an option
841
+
842
+ The options are specified by keyword arguments with their values
843
+ being a dictionary which describes the option. The
844
+ allowed/expected keys in the dictionary are:
845
+
846
+ - ``alias`` -- defines alias/synonym for option values
847
+ - ``alt_name`` -- alternative name for an option
848
+ - ``checker`` -- a function for checking whether a particular value for
849
+ the option is valid
850
+ - ``default`` -- the default value of the option
851
+ - ``description`` -- documentation string
852
+ - ``link_to`` -- links to an option for this set of options to an
853
+ option in another :class:`GlobalOptions`
854
+ - ``setter`` -- a function (class method) which is called whenever this
855
+ option changes
856
+ - ``values`` -- dictionary of the legal values for this option (this
857
+ automatically defines the corresponding ``checker``); this dictionary
858
+ gives the possible options, as keys, together with a brief description
859
+ of them
860
+ - ``case_sensitive`` -- boolean (default: ``True``); depending on whether
861
+ the values of the option are case sensitive
862
+
863
+ Options and their values can be abbreviated provided that this
864
+ abbreviation is a prefix of a unique option.
865
+
866
+ EXAMPLES::
867
+
868
+ sage: from sage.structure.global_options import GlobalOptions
869
+ sage: class Menu():
870
+ ....: class options(GlobalOptions):
871
+ ....: '''
872
+ ....: Fancy documentation
873
+ ....: -------------------
874
+ ....:
875
+ ....: @OPTIONS@
876
+ ....:
877
+ ....: End of Fancy documentation
878
+ ....: '''
879
+ ....: NAME = 'menu'
880
+ ....: entree = dict(default='soup',
881
+ ....: description='The first course of a meal',
882
+ ....: values=dict(soup='soup of the day', bread='oven baked'),
883
+ ....: alias=dict(rye='bread'))
884
+ ....: appetizer = dict(alt_name='entree')
885
+ ....: main = dict(default='pizza', description='Main meal',
886
+ ....: values=dict(pizza='thick crust', pasta='penne arrabiata'),
887
+ ....: case_sensitive=False)
888
+ ....: dessert = dict(default='espresso', description='Dessert',
889
+ ....: values=dict(espresso='life begins again',
890
+ ....: cake='waist begins again',
891
+ ....: cream='fluffy white stuff'))
892
+ ....: tip = dict(default=10, description='Reward for good service',
893
+ ....: checker=lambda tip: tip in range(20))
894
+ sage: Menu.options
895
+ Current options for menu
896
+ - dessert: espresso
897
+ - entree: soup
898
+ - main: pizza
899
+ - tip: 10
900
+ sage: Menu.options(entree='s') # unambiguous abbreviations are allowed
901
+ sage: Menu.options(t=15)
902
+ sage: (Menu.options['tip'], Menu.options('t'))
903
+ (15, 15)
904
+ sage: Menu.options()
905
+ Current options for menu
906
+ - dessert: espresso
907
+ - entree: soup
908
+ - main: pizza
909
+ - tip: 15
910
+ sage: Menu.options._reset(); Menu.options()
911
+ Current options for menu
912
+ - dessert: espresso
913
+ - entree: soup
914
+ - main: pizza
915
+ - tip: 10
916
+ sage: Menu.options.tip=40
917
+ Traceback (most recent call last):
918
+ ...
919
+ ValueError: 40 is not a valid value for tip in the options for menu
920
+ sage: Menu.options(m='p') # ambiguous abbreviations are not allowed
921
+ Traceback (most recent call last):
922
+ ...
923
+ ValueError: p is not a valid value for main in the options for menu
924
+
925
+ The documentation for the options class is automatically generated from the
926
+ information which specifies the options:
927
+
928
+ .. CODE-BLOCK:: text
929
+
930
+ Fancy documentation
931
+ -------------------
932
+
933
+ OPTIONS:
934
+
935
+ - dessert: (default: espresso)
936
+ Dessert
937
+
938
+ - ``cake`` -- waist begins again
939
+ - ``cream`` -- fluffy white stuff
940
+ - ``espresso`` -- life begins again
941
+
942
+ - entree: (default: soup)
943
+ The first course of a meal
944
+
945
+ - ``bread`` -- oven baked
946
+ - ``rye`` -- alias for bread
947
+ - ``soup`` -- soup of the day
948
+
949
+ - main: (default: pizza)
950
+ Main meal
951
+
952
+ - ``pasta`` -- penne arrabiata
953
+ - ``pizza`` -- thick crust
954
+
955
+ - tip: (default: 10)
956
+ Reward for good service
957
+
958
+ End of Fancy documentation
959
+
960
+ See :class:`~sage.structure.global_options.GlobalOptions` for more features of these options.
961
+
962
+ The possible values for an individual option can be obtained by
963
+ (trying to) set it equal to '?'::
964
+
965
+ sage: Menu.options(des='?')
966
+ - ``dessert`` -- (default: ``espresso``)
967
+ Dessert
968
+ <BLANKLINE>
969
+ - ``cake`` -- waist begins again
970
+ - ``cream`` -- fluffy white stuff
971
+ - ``espresso`` -- life begins again
972
+ <BLANKLINE>
973
+ Current value: espresso
974
+ """
975
+ __name__ = 'options'
976
+
977
+ def __init__(self, NAME=None, module='', option_class='', doc='', end_doc='', **options):
978
+ r"""
979
+ Initialize ``self``.
980
+
981
+ TESTS::
982
+
983
+ sage: from sage.structure.global_options import GlobalOptions
984
+ sage: class menu(GlobalOptions):
985
+ ....: entree = dict(default='soup',
986
+ ....: description='The first course of a meal',
987
+ ....: values=dict(soup='soup of the day', bread='oven baked'),
988
+ ....: alias=dict(rye='bread'))
989
+ ....: appetizer = dict(alt_name='entree')
990
+ ....: main = dict(default='pizza', description='Main meal',
991
+ ....: values=dict(pizza='thick crust', pasta='penne arrabiata'),
992
+ ....: case_sensitive=False)
993
+ ....: dessert = dict(default='espresso', description='Dessert',
994
+ ....: values=dict(espresso='life begins again',
995
+ ....: cake='waist begins again',
996
+ ....: cream='fluffy white stuff'))
997
+ ....: tip = dict(default=10, description='Reward for good service',
998
+ ....: checker=lambda tip: tip in range(20))
999
+ sage: menu._name # Default name is class name
1000
+ 'menu'
1001
+ sage: class specials(GlobalOptions):
1002
+ ....: entree = dict(link_to=(menu, 'entree'))
1003
+ ....: main_specials = dict(default='salmon', description='main course specials',
1004
+ ....: values=dict(salmon='a fish', crab='Sebastian'))
1005
+ sage: specials['entree'] = 'rye'
1006
+ sage: menu['entree']
1007
+ 'bread'
1008
+
1009
+ sage: class alias_test(GlobalOptions):
1010
+ ....: "Test aliases with case sensitivity"
1011
+ ....: test_opt = dict(default='Upper',
1012
+ ....: description = 'Starts with an uppercase',
1013
+ ....: values = dict(Upper="Starts with uppercase",
1014
+ ....: lower="only lowercase"),
1015
+ ....: case_sensitive = False,
1016
+ ....: alias = dict(UpperAlias='Upper', lower_alias='lower'))
1017
+ sage: alias_test['test_opt'] = 'Lower_Alias'
1018
+ sage: alias_test['test_opt']
1019
+ 'lower'
1020
+ sage: alias_test['test_opt'] = 'upperalias'
1021
+ sage: alias_test['test_opt']
1022
+ 'Upper'
1023
+ """
1024
+ if NAME is None:
1025
+ # Require a "name" keyword in **options
1026
+ try:
1027
+ NAME = options.pop("name")
1028
+ except KeyError:
1029
+ raise TypeError("GlobalOptions() is missing keyword argument 'name'")
1030
+ self._name = NAME
1031
+
1032
+ # initialise the various dictionaries used by GlobalOptions
1033
+ self._alias = {} # a dictionary of alias for the values of some options
1034
+ self._alt_names = {} # a dictionary of alternative names for some options
1035
+ self._case_sensitive = {} # a dictionary of booleans indicating to check case sensitivity
1036
+ self._checker = {} # a dictionary of validity checkers for each option
1037
+ self.__default_value = {} # a dictionary of the default options
1038
+ self._display_values = {} # a dictionary of the output of the values
1039
+ self._doc = {} # a dictionary of doc strings, forced by the linked options
1040
+ self._legal_values = {} # a dictionary of lists of the legal values for each option
1041
+ self._linked_value = {} # a dictionary of linked to other global options as (link, linked_option)
1042
+ self._setter = {} # a dictionary of the list of setters
1043
+ self._value = {} # a dictionary of the current options
1044
+ for option in options:
1045
+ self._add_option(option, options[option])
1046
+
1047
+ self._options_module = module
1048
+ self._option_class = option_class or self._name
1049
+
1050
+ # If the instance dict has a __doc__ attribute, use that as
1051
+ # docstring.
1052
+ try:
1053
+ self._docstring = dedent(self.__dict__.pop("__doc__"))
1054
+ except KeyError:
1055
+ self._docstring = "@OPTIONS@"
1056
+
1057
+ # Finally, we build the doc string for the options
1058
+ # First we strip common white space off the front of doc and end_doc
1059
+ if doc:
1060
+ self._docstring = dedent(doc) + "\n\n" + self._docstring
1061
+
1062
+ if end_doc:
1063
+ self._docstring = self._docstring + "\n\n" + dedent(end_doc)
1064
+
1065
+ # Add docstring footer
1066
+ self._docstring += "\nSee :class:`~sage.structure.global_options.GlobalOptions` for more features of these options."
1067
+
1068
+ def __repr__(self):
1069
+ r"""
1070
+ Return a string representation for this collection of options.
1071
+
1072
+ EXAMPLES::
1073
+
1074
+ sage: from sage.structure.global_options import GlobalOptions
1075
+ sage: class FoodOptions(GlobalOptions):
1076
+ ....: NAME = 'daily meal'
1077
+ ....: food = dict(default='apple', values=dict(apple='a fruit', pair='of what?'))
1078
+ ....: drink = dict(default='water', values=dict(water='a drink', coffee='a lifestyle'))
1079
+ sage: FoodOptions
1080
+ Current options for daily meal
1081
+ - drink: water
1082
+ - food: apple
1083
+ """
1084
+ options = list(self._value) + list(self._linked_value)
1085
+ for x in self._alt_names:
1086
+ options.remove(x)
1087
+ if not options:
1088
+ return 'Current options for {}'.format(self._name)
1089
+
1090
+ options.sort()
1091
+ width = 1 + max(len(option) for option in options)
1092
+ txt = '\n'.join(' - {:{}} {}'.format(option + ':', width, self[option])
1093
+ for option in options)
1094
+ return 'Current options for {}\n{}'.format(self._name, txt)
1095
+
1096
+ def __call__(self, *get_value, **set_value):
1097
+ r"""
1098
+ Get or set value of the option ``option``.
1099
+
1100
+ EXAMPLES::
1101
+
1102
+ sage: from sage.structure.global_options import GlobalOptions
1103
+ sage: class FoodOptions(GlobalOptions):
1104
+ ....: NAME = 'daily meal'
1105
+ ....: food = dict(default='apple', values=dict(apple='a fruit', pair='of what?'))
1106
+ ....: drink = dict(default='water', values=dict(water='a drink', coffee='a lifestyle'))
1107
+ ....: beverage = dict(alt_name='drink')
1108
+ sage: FoodOptions()
1109
+ Current options for daily meal
1110
+ - drink: water
1111
+ - food: apple
1112
+ sage: FoodOptions('food')
1113
+ 'apple'
1114
+ sage: FoodOptions(food='pair'); FoodOptions()
1115
+ Current options for daily meal
1116
+ - drink: water
1117
+ - food: pair
1118
+ sage: FoodOptions('beverage')
1119
+ 'water'
1120
+ sage: FoodOptions(food='apple', drink='coffee'); FoodOptions()
1121
+ Current options for daily meal
1122
+ - drink: coffee
1123
+ - food: apple
1124
+ """
1125
+ if not get_value and not set_value:
1126
+ return self
1127
+
1128
+ if get_value:
1129
+ # use __getitem__ to return these options
1130
+ if len(get_value) == 1:
1131
+ return self[get_value[0]]
1132
+ else:
1133
+ return [self[option] for option in get_value]
1134
+
1135
+ # use __setitem__ to set these options
1136
+ if set_value:
1137
+ for option in set_value:
1138
+ self[option] = set_value[option]
1139
+
1140
+ def __getitem__(self, option):
1141
+ r"""
1142
+ Return the current value of the option ``option``.
1143
+
1144
+ EXAMPLES::
1145
+
1146
+ sage: from sage.structure.global_options import GlobalOptions
1147
+ sage: class FoodOptions(GlobalOptions):
1148
+ ....: NAME = 'daily meal'
1149
+ ....: food = dict(default='apple', values=dict(apple='a fruit', pair='of what?'))
1150
+ ....: drink = dict(default='water', values=dict(water='a drink', coffee='a lifestyle'))
1151
+ sage: FoodOptions['drink']
1152
+ 'water'
1153
+ sage: FoodOptions['d']
1154
+ 'water'
1155
+ """
1156
+ option = self._match_option(option)
1157
+ if option in self._linked_value:
1158
+ link, linked_opt = self._linked_value[option]
1159
+ return link[linked_opt]
1160
+ elif option in self._value:
1161
+ if option in self._display_values:
1162
+ return self._display_values[option][self._value[option]]
1163
+ return self._value[option]
1164
+
1165
+ def __setitem__(self, option, value):
1166
+ r"""
1167
+ The ``__setitem__`` method is used to change the current values of the
1168
+ options. It also checks that the supplied options are valid and changes
1169
+ any alias to its generic value.
1170
+
1171
+ EXAMPLES::
1172
+
1173
+ sage: from sage.structure.global_options import GlobalOptions
1174
+ sage: class FoodOptions(GlobalOptions):
1175
+ ....: NAME = 'daily meal'
1176
+ ....: food = dict(default='apple', values=dict(apple='a fruit', pair='of what?'))
1177
+ ....: drink = dict(default='water', values=dict(water='a drink', coffee='a lifestyle'))
1178
+ sage: FoodOptions['drink']='coffee'; FoodOptions()
1179
+ Current options for daily meal
1180
+ - drink: coffee
1181
+ - food: apple
1182
+ sage: FoodOptions(drink='w'); FoodOptions()
1183
+ Current options for daily meal
1184
+ - drink: water
1185
+ - food: apple
1186
+ sage: FoodOptions(drink='?')
1187
+ - ``drink`` -- (default: ``water``)
1188
+ <BLANKLINE>
1189
+ - ``coffee`` -- a lifestyle
1190
+ - ``water`` -- a drink
1191
+ <BLANKLINE>
1192
+ Current value: water
1193
+ """
1194
+ option = self._match_option(option)
1195
+ if not callable(value):
1196
+ value = self._match_value(option, value)
1197
+
1198
+ if value == '?': # return help
1199
+ print('%s\nCurrent value: %s' % (self._doc[option], self[option]))
1200
+ return # we do not want to call the setter below
1201
+
1202
+ elif option in self._linked_value:
1203
+ link, linked_opt = self._linked_value[option]
1204
+ link[linked_opt] = value
1205
+
1206
+ else:
1207
+ self._value[option] = value
1208
+
1209
+ if option in self._setter:
1210
+ # if a setter function exists then call it with the associated
1211
+ # class, option and value
1212
+ self._setter[option](option, value)
1213
+
1214
+ def _instancedoc_(self):
1215
+ r"""
1216
+ Return the docstring for the options class ``self``.
1217
+
1218
+ EXAMPLES::
1219
+
1220
+ sage: print(Partitions.options.__doc__)
1221
+ <BLANKLINE>
1222
+ Set and display the global options for elements of the partition,
1223
+ skew partition, and partition tuple classes. If no parameters are
1224
+ set, then the function returns a copy of the options dictionary.
1225
+ <BLANKLINE>
1226
+ The ``options`` to partitions can be accessed as the method
1227
+ :obj:`Partitions.options` of :class:`Partitions` and
1228
+ related parent classes.
1229
+ <BLANKLINE>
1230
+ <BLANKLINE>
1231
+ OPTIONS:
1232
+ <BLANKLINE>
1233
+ - ``convention`` -- (default: ``English``)
1234
+ Sets the convention used for displaying tableaux and partitions
1235
+ <BLANKLINE>
1236
+ - ``English`` -- use the English convention
1237
+ - ``French`` -- use the French convention
1238
+ ...
1239
+
1240
+ TESTS::
1241
+
1242
+ sage: from sage.structure.global_options import GlobalOptions
1243
+ sage: print(GlobalOptions.__doc__)
1244
+ <BLANKLINE>
1245
+ The :class:`GlobalOptions` class is a generic class for setting...
1246
+ """
1247
+ options = 'OPTIONS:\n\n{}\n\n'.format('\n'.join(self._doc[opt] for opt in sorted(self._doc)))
1248
+ return self._docstring.replace("@OPTIONS@", options)
1249
+
1250
+ def __setattr__(self, name, value=None):
1251
+ r"""
1252
+ Set the attribute ``name`` of the option class ``self`` equal to
1253
+ ``value``, if the attribute ``name`` exists.
1254
+
1255
+ As the attributes of an option class are the actual options we need
1256
+ to be able to "trap" invalid options in a sensible way. We do this
1257
+ by sending any "non-standard" to :meth:`__setitem__` for processing.
1258
+
1259
+ EXAMPLES::
1260
+
1261
+ sage: Partitions.options.display = 'exp'
1262
+ sage: Partitions.options.dispplay = 'list'
1263
+ Traceback (most recent call last):
1264
+ ...
1265
+ ValueError: dispplay is not an option for Partitions
1266
+ sage: Partitions.options._reset()
1267
+ """
1268
+ # Underscore, and "special", attributes are set using type.__setattr__
1269
+ if name[0] == '_' or name in ['reset', 'dispatch', 'default_value']:
1270
+ return super().__setattr__(name, value)
1271
+
1272
+ # General case: redirect to __setitem__
1273
+ self[name] = value
1274
+
1275
+ def __setstate__(self, state):
1276
+ r"""
1277
+ This is a custom :meth:`__setstate__` method for unpickling instances of
1278
+ the :class:`GlobalOptions` class.
1279
+
1280
+ The :meth:`__getstate__` method returns a dictionary with an
1281
+ ``options_class`` key which identifies the "parent" class for the options.
1282
+ This is then used to unpickle the options class.
1283
+
1284
+ EXAMPLES::
1285
+
1286
+ sage: # needs sage.combinat
1287
+ sage: Partitions.options()
1288
+ Current options for Partitions
1289
+ - convention: English
1290
+ - diagram_str: *
1291
+ - display: list
1292
+ - latex: young_diagram
1293
+ - latex_diagram_str: \ast
1294
+ sage: Partitions.options.convention = "French"
1295
+ sage: pickle = dumps(Partitions.options)
1296
+ sage: Partitions.options._reset() # reset options
1297
+ sage: loads(pickle) # indirect doctest
1298
+ Current options for Partitions
1299
+ - convention: French
1300
+ - diagram_str: *
1301
+ - display: list
1302
+ - latex: young_diagram
1303
+ - latex_diagram_str: \ast
1304
+ sage: Partitions.options._reset()
1305
+ """
1306
+ # open the options for the corresponding "parent" and copy all of
1307
+ # the data from its options class into unpickle
1308
+ options_class = getattr(import_module(state['options_module']), state['option_class'])
1309
+ unpickle = options_class.options
1310
+ state.pop('option_class')
1311
+ state.pop('options_module')
1312
+ for setting in unpickle.__dict__:
1313
+ self.__dict__[setting] = unpickle.__dict__[setting]
1314
+
1315
+ # reset the options in ``self`` to their defaults
1316
+ self._reset()
1317
+ # apply the options stored in state
1318
+ for opt in state:
1319
+ self[opt] = state[opt]
1320
+ options_class.options = self
1321
+
1322
+ def __getstate__(self):
1323
+ r"""
1324
+ Return a dictionary that can be used to pickle an instance of a
1325
+ :class:`GlobalOptions` class.
1326
+
1327
+ This is called by :func:`pickle_GlobalOptions`.
1328
+
1329
+ Typically instances of :class:`GlobalOptions` are
1330
+ complicated to create, so they do no pickle. If the options are
1331
+ associated to "parent" class then it is possible to create the
1332
+ default version of the class and then add the non-default
1333
+ settings on top of this. This method returns a dictionary of the
1334
+ non-default options that can then be used to unpickle an
1335
+ instance of the option using :func:`unpickle_GlobalOptions`.
1336
+
1337
+ EXAMPLES::
1338
+
1339
+ sage: Partitions.options._reset()
1340
+ sage: Partitions.options.__getstate__()
1341
+ {'convention': 'English',
1342
+ 'option_class': 'Partitions',
1343
+ 'options_module': 'sage.combinat.partition'}
1344
+ """
1345
+
1346
+ # options classes can be pickled only if they are the options for an
1347
+ # associated "parent" class that lives in self._module
1348
+
1349
+ if not self._options_module:
1350
+ pickleable = False
1351
+ else:
1352
+ opt_mod = import_module(self._options_module)
1353
+ pickleable = hasattr(opt_mod, self._name) and hasattr(getattr(opt_mod, self._name), 'options')
1354
+
1355
+ if not pickleable:
1356
+ raise PicklingError('%s cannot be pickled because it is not associated with a class' % self)
1357
+
1358
+ pickle = {'option_class': self._option_class, 'options_module': self._options_module}
1359
+ for opt in self._value:
1360
+ if opt not in self._alt_names and self[opt] != self.__default_value[opt]:
1361
+ pickle[opt] = self[opt]
1362
+ for opt in self._linked_value:
1363
+ link, linked_opt = self._linked_value[opt]
1364
+ if opt not in self._alt_names and link[opt] != link.__default_value[opt]:
1365
+ pickle[opt] = self[opt]
1366
+ return pickle
1367
+
1368
+ def __eq__(self, other):
1369
+ r"""
1370
+ Two options classes are equal if they return the same :meth:`__getstate__`.
1371
+
1372
+ EXAMPLES::
1373
+
1374
+ sage: Partitions.options == PartitionsGreatestLE.options # indirect doctest
1375
+ True
1376
+ sage: Partitions.options == Tableaux.options # needs sage.combinat
1377
+ False
1378
+ """
1379
+ return isinstance(other, GlobalOptions) and self.__getstate__() == other.__getstate__()
1380
+
1381
+ def _add_option(self, option, specifications):
1382
+ r"""
1383
+ Add an option.
1384
+
1385
+ INPUT:
1386
+
1387
+ - ``option`` -- string
1388
+ - ``specifications`` -- dictionary
1389
+
1390
+ .. SEEALSO::
1391
+
1392
+ :class:`GlobalOptions` for a description of the required
1393
+ ``specifications``.
1394
+ """
1395
+ if not isinstance(specifications, dict):
1396
+ raise TypeError("expected dict as specification of %r, got %r" % (option, specifications))
1397
+
1398
+ doc = {} # will be used to build the doc string
1399
+ self._case_sensitive[option] = True # ``True`` by default
1400
+ self._legal_values[option] = []
1401
+ for spec in sorted(specifications): # NB: options processed alphabetically!
1402
+ if spec == 'alias':
1403
+ self._alias[option] = specifications[spec]
1404
+ self._legal_values[option] += list(specifications[spec])
1405
+ for opt in specifications[spec]:
1406
+ doc[opt] = 'alias for ``%s``' % specifications[spec][opt]
1407
+ elif spec == 'alt_name':
1408
+ self._alt_names[option] = specifications[spec]
1409
+ self._linked_value[option] = (self, specifications[spec])
1410
+ doc = '- ``%s`` -- alternative name for ``%s``' % (option, specifications[spec].lower())
1411
+ elif spec == 'case_sensitive':
1412
+ if not specifications[spec]:
1413
+ for opt in self._legal_values:
1414
+ self._display_values[option] = {val.lower(): val for val in self._legal_values[option]}
1415
+ self._legal_values[option] = [val.lower() for val in self._legal_values[option]]
1416
+ if option in self._alias:
1417
+ self._alias[option] = {k.lower(): v.lower()
1418
+ for k, v in self._alias[option].items()}
1419
+ self._case_sensitive[option] = bool(specifications[spec])
1420
+ elif spec == 'checker':
1421
+ if not callable(specifications[spec]):
1422
+ raise ValueError('the checker for %s must be callable' % option)
1423
+ self._checker[option] = specifications[spec]
1424
+ elif spec == 'default':
1425
+ self.__default_value[option] = specifications[spec]
1426
+ elif spec == 'link_to':
1427
+ if (isinstance(specifications[spec], tuple) and
1428
+ len(specifications[spec]) == 2 and
1429
+ isinstance(specifications[spec][0], GlobalOptions)):
1430
+ link, linked_opt = specifications['link_to'] # for sanity
1431
+ if linked_opt in link._value:
1432
+ self._linked_value[option] = specifications['link_to']
1433
+ link, linked_opt = specifications['link_to'] # for sanity
1434
+ doc = link._doc[linked_opt]
1435
+ elif linked_opt in link._linked_value:
1436
+ self._linked_value[option] = link._linked_value[linked_opt]
1437
+ doc = link._doc[linked_opt]
1438
+ else:
1439
+ raise ValueError("could not find link to {1} in {0}".format(*specifications[spec]))
1440
+ else:
1441
+ raise ValueError("linked options must be specified as a string: 'linked_option' or a tuple: (link,linked_option)")
1442
+ elif spec == 'setter':
1443
+ if callable(specifications[spec]):
1444
+ self._setter[option] = specifications[spec]
1445
+ else:
1446
+ raise ValueError('the setter for %s must be a function' % option)
1447
+ elif spec == 'values':
1448
+ for val in specifications[spec]:
1449
+ doc[val] = specifications[spec][val]
1450
+ doc.update(specifications[spec])
1451
+ if self._case_sensitive[option]:
1452
+ self._legal_values[option] += list(specifications[spec])
1453
+ self._display_values[option] = {val: val for val in specifications[spec]}
1454
+ else:
1455
+ self._legal_values[option] += [val.lower() for val in specifications[spec]]
1456
+ self._display_values[option] = {val.lower(): val for val in specifications[spec]}
1457
+ elif spec != 'description':
1458
+ raise ValueError('Initialization error in Global options for %s: %s not recognized!' % (self._name, spec))
1459
+
1460
+ # now build the doc string for this option
1461
+ if doc == {} and 'description' not in specifications:
1462
+ raise ValueError('no documentation specified for %s in the options for %s' % (option, self._name))
1463
+
1464
+ # first a necessary hack to initialise the option in self._doc because __setitem__ calls _match_option
1465
+ self._doc[option] = ''
1466
+ if option in self._linked_value:
1467
+ self._doc[option] = doc
1468
+ else:
1469
+ width = max(len(v) for v in doc) + 4 if doc != {} else 4
1470
+ if len(doc) > 0:
1471
+ self._doc[option] = '- ``{}`` -- (default: ``{}``)\n{}\n{}\n'.format(
1472
+ option, self._default_value(option),
1473
+ ' %s\n' % specifications['description'] if 'description' in specifications else '',
1474
+ '\n'.join(' - {:{}} -- {}'.format('``' + val + '``', width, doc[val])
1475
+ for val in sorted(doc)))
1476
+ else:
1477
+ self._doc[option] = '- ``{}`` -- (default: ``{}``)\n{}'.format(
1478
+ option, self._default_value(option),
1479
+ ' %s\n' % specifications['description'] if 'description' in specifications else '')
1480
+
1481
+ # sanity check for non-linked options
1482
+ if option not in self._linked_value:
1483
+ if 'default' not in specifications:
1484
+ raise ValueError('a default value for %s must be given' % option)
1485
+
1486
+ if not (option in self._checker or option in self._legal_values):
1487
+ raise ValueError('a value checker or a list of valid values for %s must be given' % option)
1488
+
1489
+ # finally, set, check and process the default value using __setitem__
1490
+ self[option] = self.__default_value[option]
1491
+ self.__default_value[option] = self._value[option] # in case the default is an alias
1492
+
1493
+ # Build getters and setters for this option. As we have
1494
+ # overridden __setattr__, we call object.__setattr__ directly
1495
+ super().__setattr__(option, Option(self, option))
1496
+
1497
+ def _match_option(self, option):
1498
+ r"""
1499
+ Check whether ``option`` is the name of an option of ``self``, or a
1500
+ prefix thereof.
1501
+
1502
+ INPUT:
1503
+
1504
+ - ``option`` -- string
1505
+
1506
+ EXAMPLES::
1507
+
1508
+ sage: from sage.structure.global_options import GlobalOptions
1509
+ sage: class FoodOptions(GlobalOptions):
1510
+ ....: NAME = 'daily meal'
1511
+ ....: food = dict(default='apple', values=dict(apple='a fruit', pair='of what?'))
1512
+ ....: drink = dict(default='water', values=dict(water='a drink', coffee='a lifestyle'))
1513
+ sage: FoodOptions('food') # indirect doctest
1514
+ 'apple'
1515
+ sage: FoodOptions('f')
1516
+ 'apple'
1517
+ """
1518
+ if option in self._doc:
1519
+ return option
1520
+
1521
+ # a lower case version of the option
1522
+ loption = option.lower()
1523
+
1524
+ # as it is not an option try and match it with a prefix to an option,
1525
+ # without checking case using the fact that the keys of self._doc is a
1526
+ # list of the options, both normal and linked
1527
+ matches = [opt for opt in self._doc if opt.lower().startswith(loption)]
1528
+ if matches and all(m.startswith(matches[0]) for m in matches):
1529
+ return matches[0]
1530
+ elif len(matches) > 1:
1531
+ # as there is more than one match check case as well
1532
+ matches = [mat for mat in matches if mat.startswith(option)]
1533
+ if matches and all(m.startswith(matches[0]) for m in matches):
1534
+ return matches[0]
1535
+ else:
1536
+ raise ValueError('%s is an ambiguous option for %s' % (option, self._name))
1537
+
1538
+ # if we are still here this is not a good option!
1539
+ raise ValueError('%s is not an option for %s' % (option, self._name))
1540
+
1541
+ def _match_value(self, option, value):
1542
+ r"""
1543
+ Check whether ``value`` is a valid value for ``option``.
1544
+
1545
+ INPUT:
1546
+
1547
+ - ``option`` -- string: the name of an option, or prefix thereof
1548
+ - ``value`` -- a value or ``'?'``
1549
+
1550
+ EXAMPLES::
1551
+
1552
+ sage: from sage.structure.global_options import GlobalOptions
1553
+ sage: class FoodOptions(GlobalOptions):
1554
+ ....: NAME = 'daily meal'
1555
+ ....: food = dict(default='apple', values=dict(apple='a fruit', pair='of what?'))
1556
+ ....: drink = dict(default='water', values=dict(water='a drink', wine='a lifestyle'))
1557
+ sage: FoodOptions(f='a') # indirect doctest
1558
+ sage: FoodOptions('f')
1559
+ 'apple'
1560
+ sage: FoodOptions(d='wi'); FoodOptions('f')
1561
+ 'apple'
1562
+ sage: FoodOptions(d='w')
1563
+ Traceback (most recent call last):
1564
+ ...
1565
+ ValueError: w is not a valid value for drink in the options for daily meal
1566
+ """
1567
+ if value == "?":
1568
+ return value # help on this value
1569
+
1570
+ if option in self._linked_value:
1571
+ link, linked_opt = self._linked_value[option]
1572
+ return link._match_value(linked_opt, value)
1573
+
1574
+ orig_value = value
1575
+
1576
+ # convert to proper case if it is a string
1577
+ if isinstance(value, str) and not self._case_sensitive[option]:
1578
+ value = value.lower()
1579
+
1580
+ if option in self._legal_values:
1581
+ if value in self._legal_values[option]:
1582
+ if option in self._alias and value in self._alias[option]:
1583
+ return self._alias[option][value]
1584
+ return value
1585
+
1586
+ # as it is not a value try and match it with a prefix of a value
1587
+ matches = [val for val in self._legal_values[option] if val.startswith(value)]
1588
+ if matches and all(m.startswith(matches[0]) for m in matches):
1589
+ val = matches[0]
1590
+ if option in self._alias and val in self._alias[option]:
1591
+ return self._alias[option][val]
1592
+ return val
1593
+
1594
+ if option in self._checker and self._checker[option](value):
1595
+ return value
1596
+
1597
+ # if we are still here this is not a good value!
1598
+
1599
+ # replace any value alias with its "real" value
1600
+ if option in self._alias and value in self._alias[option]:
1601
+ orig_value = self._alias[option][value]
1602
+ raise ValueError('%s is not a valid value for %s in the options for %s' % (orig_value, option, self._name))
1603
+
1604
+ def _default_value(self, option):
1605
+ r"""
1606
+ Return the default value of the option.
1607
+
1608
+ EXAMPLES::
1609
+
1610
+ sage: from sage.structure.global_options import GlobalOptions
1611
+ sage: class FoodOptions(GlobalOptions):
1612
+ ....: NAME = 'daily meal'
1613
+ ....: food = dict(default='apple', values=dict(apple='a fruit', pair='of what?'))
1614
+ ....: drink = dict(default='water', values=dict(water='a drink', coffee='a lifestyle'))
1615
+ sage: FoodOptions._default_value('food')
1616
+ 'apple'
1617
+ """
1618
+ option = self._match_option(option)
1619
+ if option in self.__default_value:
1620
+ return self.__default_value[option]
1621
+ else:
1622
+ link, linked_opt = self._linked_value[option]
1623
+ return link._default_value(linked_opt)
1624
+
1625
+ def _dispatch(self, obj, dispatch_to, option, *args, **kargs):
1626
+ r"""
1627
+ The *dispatchable* options are options which dispatch related methods of
1628
+ the corresponding class - or user defined methods which are passed to
1629
+ :class:`GlobalOptions`. The format for specifying a dispatchable option
1630
+ is to include ``dispatch_to = <option name>`` in the specifications for
1631
+ the options and then to add the options to the (element) class. Each
1632
+ option is then assumed to be a method of the element class with a name
1633
+ of the form ``<option name> + '_' + <current vale for this option'``.
1634
+ These options are called by the element class via::
1635
+
1636
+ return self.options._dispatch(self, dispatch_to, option, *args, **kargs)
1637
+
1638
+ Note that the argument ``self`` is necessary here because the
1639
+ dispatcher is a method of the options class and not of
1640
+ ``self``. The value of the option can also be set to a
1641
+ user-defined function, with arguments ``self`` and ``option``;
1642
+ in this case the user's function is called instead.
1643
+
1644
+ EXAMPLES:
1645
+
1646
+ Here is a contrived example::
1647
+
1648
+ sage: from sage.structure.global_options import GlobalOptions
1649
+ sage: class DelimitedListOptions(GlobalOptions):
1650
+ ....: delim=dict(default='b', values={'b':'brackets', 'p':'parentheses'})
1651
+ sage: class DelimitedList(SageObject):
1652
+ ....: options = DelimitedListOptions
1653
+ ....: def __init__(self, L):
1654
+ ....: self._list = L
1655
+ ....: def _repr_b(self): return '[%s]' % ','.join('%s'%i for i in self._list)
1656
+ ....: def _repr_p(self): return '(%s)' % ','.join('%s'%i for i in self._list)
1657
+ ....: def _repr_(self): return self.options._dispatch(self, '_repr_','delim')
1658
+ sage: dlist = DelimitedList([1,2,3]); dlist
1659
+ [1,2,3]
1660
+ sage: dlist.options.delim='p'; dlist
1661
+ (1,2,3)
1662
+ sage: dlist.options(delim=lambda self: '<%s>' % ','.join('%s'%i for i in self._list)); dlist
1663
+ <1,2,3>
1664
+ """
1665
+ if callable(self._value[option]):
1666
+ try:
1667
+ return self._value[option](obj, *args, **kargs)
1668
+ except TypeError:
1669
+ raise ValueError('the user defined dispatcher function failed!')
1670
+ else:
1671
+ if dispatch_to[-1] == '_':
1672
+ dispatch_to = dispatch_to[:-1]
1673
+ dispatch = getattr(obj, dispatch_to + '_' + self._value[option])
1674
+ return dispatch(*args, **kargs)
1675
+
1676
+ raise ValueError('%s is not a dispatchable option!' % option)
1677
+
1678
+ def _reset(self, option=None):
1679
+ r"""
1680
+ Reset options to their default value.
1681
+
1682
+ INPUT:
1683
+
1684
+ - ``option`` -- (default: ``None``) the name of an option as a string
1685
+ or ``None``. If ``option`` is specified only this option is reset to
1686
+ its default value; otherwise all options are reset.
1687
+
1688
+ EXAMPLES::
1689
+
1690
+ sage: from sage.structure.global_options import GlobalOptions
1691
+ sage: class Meal():
1692
+ ....: class options(GlobalOptions):
1693
+ ....: NAME = 'daily meal'
1694
+ ....: food = dict(default='bread', values=dict(bread='rye bread', salmon='a fish'))
1695
+ ....: drink = dict(default='water',values=dict(water='essential for life', wine='essential'))
1696
+ sage: Meal.options.food='salmon'; Meal.options
1697
+ Current options for daily meal
1698
+ - drink: water
1699
+ - food: salmon
1700
+ sage: Meal.options._reset('drink'); Meal.options()
1701
+ Current options for daily meal
1702
+ - drink: water
1703
+ - food: salmon
1704
+ sage: Meal.options._reset(); Meal.options()
1705
+ Current options for daily meal
1706
+ - drink: water
1707
+ - food: bread
1708
+ """
1709
+ if option is None:
1710
+ for option in self.__default_value:
1711
+ self._value[option] = self.__default_value[option]
1712
+ if not self._case_sensitive[option] and isinstance(self._value[option], str):
1713
+ self._value[option] = self._value[option].lower()
1714
+ for option in self._linked_value:
1715
+ link, linked_opt = self._linked_value[option]
1716
+ link._reset(linked_opt)
1717
+ else:
1718
+ option = self._match_option(option)
1719
+ if option in self.__default_value:
1720
+ self._value[option] = self.__default_value[option]
1721
+ if not self._case_sensitive[option] and isinstance(self._value[option], str):
1722
+ self._value[option] = self._value[option].lower()
1723
+ elif option in self._linked_value:
1724
+ link, linked_opt = self._linked_value[option]
1725
+ link._reset(linked_opt)