From 3279bdc83784961786494580b003d3356b67a9d7 Mon Sep 17 00:00:00 2001 From: Wilfried Luebbe Date: Fri, 28 Mar 2014 20:14:49 +0100 Subject: [PATCH] first run of futurize -w -f raise --- src/bin/sage-num-threads.py | 4 +- src/doc/common/inventory_builder.py | 2 +- .../finite_dimensional_algebra.py | 2 +- src/sage/algebras/free_algebra.py | 2 +- .../algebras/quatalg/quaternion_algebra.py | 16 +-- .../algebras/steenrod/steenrod_algebra.py | 2 +- src/sage/categories/affine_weyl_groups.py | 2 +- src/sage/categories/algebra_ideals.py | 2 +- src/sage/categories/algebra_modules.py | 2 +- src/sage/categories/algebras_with_basis.py | 2 +- src/sage/categories/category.py | 6 +- src/sage/categories/classical_crystals.py | 2 +- .../categories/commutative_algebra_ideals.py | 2 +- .../categories/commutative_ring_ideals.py | 2 +- src/sage/categories/coxeter_groups.py | 30 ++-- src/sage/categories/crystals.py | 6 +- src/sage/categories/enumerated_sets.py | 10 +- src/sage/categories/examples/facade_sets.py | 2 +- .../examples/infinite_enumerated_sets.py | 2 +- src/sage/categories/examples/sets_cat.py | 2 +- src/sage/categories/facade_sets.py | 4 +- src/sage/categories/fields.py | 6 +- src/sage/categories/finite_enumerated_sets.py | 2 +- src/sage/categories/finite_fields.py | 2 +- src/sage/categories/function_fields.py | 2 +- src/sage/categories/hecke_modules.py | 4 +- src/sage/categories/homset.py | 20 +-- .../categories/infinite_enumerated_sets.py | 4 +- src/sage/categories/modules_with_basis.py | 6 +- src/sage/categories/number_fields.py | 2 +- src/sage/categories/polyhedra.py | 2 +- src/sage/categories/pushout.py | 50 +++---- src/sage/categories/quotient_fields.py | 4 +- src/sage/categories/ring_ideals.py | 2 +- src/sage/categories/rings.py | 10 +- src/sage/categories/schemes.py | 2 +- src/sage/categories/semigroups.py | 2 +- src/sage/categories/sets_cat.py | 2 +- src/sage/categories/vector_spaces.py | 2 +- src/sage/categories/weyl_groups.py | 16 +-- src/sage/coding/code_constructions.py | 38 ++--- src/sage/coding/linear_code.py | 10 +- src/sage/combinat/affine_permutation.py | 2 +- .../combinat/binary_recurrence_sequences.py | 4 +- src/sage/combinat/binary_tree.py | 2 +- src/sage/combinat/choose_nk.py | 8 +- .../quiver_mutation_type.py | 8 +- src/sage/combinat/combinat.py | 20 +-- src/sage/combinat/combinatorial_algebra.py | 8 +- src/sage/combinat/combinatorial_map.py | 2 +- src/sage/combinat/composition.py | 2 +- src/sage/combinat/composition_tableau.py | 2 +- src/sage/combinat/crystals/direct_sum.py | 2 +- src/sage/combinat/crystals/fast_crystals.py | 2 +- src/sage/combinat/crystals/littelmann_path.py | 2 +- src/sage/combinat/crystals/tensor_product.py | 2 +- src/sage/combinat/designs/covering_design.py | 2 +- src/sage/combinat/designs/ext_rep.py | 8 +- src/sage/combinat/e_one_star.py | 28 ++-- src/sage/combinat/finite_state_machine.py | 71 +++++----- src/sage/combinat/free_module.py | 10 +- src/sage/combinat/graph_path.py | 12 +- src/sage/combinat/integer_vector.py | 6 +- .../combinat/integer_vectors_mod_permgroup.py | 4 +- src/sage/combinat/k_tableau.py | 10 +- src/sage/combinat/knutson_tao_puzzles.py | 2 +- src/sage/combinat/ncsf_qsym/qsym.py | 4 +- src/sage/combinat/permutation.py | 2 +- src/sage/combinat/posets/lattices.py | 6 +- src/sage/combinat/posets/linear_extensions.py | 4 +- src/sage/combinat/posets/posets.py | 22 +-- .../combinat/root_system/branching_rules.py | 8 +- .../combinat/root_system/dynkin_diagram.py | 12 +- .../root_system/root_lattice_realizations.py | 50 +++---- src/sage/combinat/root_system/root_space.py | 8 +- src/sage/combinat/root_system/type_E.py | 2 +- src/sage/combinat/root_system/weyl_group.py | 6 +- src/sage/combinat/schubert_polynomial.py | 10 +- src/sage/combinat/sf/classical.py | 6 +- src/sage/combinat/sf/hall_littlewood.py | 2 +- src/sage/combinat/sf/jack.py | 2 +- src/sage/combinat/sf/kfpoly.py | 6 +- src/sage/combinat/sf/llt.py | 6 +- src/sage/combinat/sf/macdonald.py | 6 +- src/sage/combinat/sf/monomial.py | 2 +- src/sage/combinat/sf/new_kschur.py | 10 +- src/sage/combinat/sf/ns_macdonald.py | 10 +- src/sage/combinat/skew_tableau.py | 2 +- src/sage/combinat/sloane_functions.py | 10 +- src/sage/combinat/species/misc.py | 2 +- .../combinat/species/recursive_species.py | 4 +- src/sage/combinat/species/series.py | 12 +- src/sage/combinat/species/series_order.py | 32 ++--- src/sage/combinat/species/species.py | 16 +-- src/sage/combinat/species/stream.py | 4 +- src/sage/combinat/subset.py | 2 +- src/sage/combinat/subword.py | 2 +- .../symmetric_group_representations.py | 6 +- src/sage/combinat/tableau.py | 6 +- src/sage/combinat/tableau_tuple.py | 16 +-- src/sage/combinat/words/abstract_word.py | 16 +-- src/sage/combinat/words/finite_word.py | 42 +++--- src/sage/combinat/words/morphism.py | 50 +++---- src/sage/combinat/words/paths.py | 20 +-- src/sage/combinat/words/suffix_trees.py | 12 +- src/sage/combinat/words/word_generators.py | 30 ++-- .../combinat/words/word_infinite_datatypes.py | 20 +-- src/sage/combinat/words/word_options.py | 14 +- src/sage/combinat/words/words.py | 24 ++-- src/sage/crypto/block_cipher/miniaes.py | 82 +++++------ src/sage/crypto/block_cipher/sdes.py | 74 +++++----- src/sage/crypto/classical_cipher.py | 20 +-- src/sage/crypto/cryptosystem.py | 2 +- src/sage/crypto/lfsr.py | 6 +- src/sage/crypto/mq/sbox.py | 6 +- src/sage/crypto/mq/sr.py | 36 ++--- src/sage/crypto/stream.py | 21 ++- src/sage/crypto/stream_cipher.py | 8 +- src/sage/databases/oeis.py | 2 +- src/sage/finance/easter.py | 2 +- src/sage/functions/bessel.py | 30 ++-- src/sage/functions/other.py | 8 +- src/sage/functions/piecewise.py | 10 +- src/sage/functions/special.py | 12 +- src/sage/games/hexad.py | 2 +- src/sage/games/quantumino.py | 2 +- src/sage/geometry/lattice_polytope.py | 83 ++++++----- src/sage/geometry/polyhedron/backend_cdd.py | 4 +- src/sage/geometry/polyhedron/base.py | 14 +- src/sage/geometry/polyhedron/library.py | 2 +- src/sage/geometry/polyhedron/misc.py | 2 +- src/sage/geometry/polyhedron/plot.py | 14 +- .../geometry/polyhedron/representation.py | 6 +- src/sage/geometry/polytope.py | 12 +- src/sage/geometry/toric_lattice.py | 6 +- src/sage/geometry/triangulation/element.py | 3 +- .../triangulation/point_configuration.py | 14 +- src/sage/graphs/digraph.py | 2 +- src/sage/graphs/digraph_generators.py | 4 +- src/sage/graphs/generators/families.py | 10 +- src/sage/graphs/generators/random.py | 4 +- src/sage/graphs/graph.py | 2 +- src/sage/graphs/graph_coloring.py | 8 +- src/sage/graphs/graph_database.py | 4 +- src/sage/graphs/graph_list.py | 2 +- src/sage/graphs/linearextensions.py | 2 +- src/sage/groups/abelian_gps/abelian_group.py | 12 +- .../abelian_gps/abelian_group_morphism.py | 10 +- .../groups/abelian_gps/dual_abelian_group.py | 4 +- .../additive_abelian_group.py | 2 +- .../additive_abelian_wrapper.py | 4 +- src/sage/groups/generic.py | 42 +++--- src/sage/groups/group_homset.py | 2 +- .../groups/matrix_gps/finitely_generated.py | 4 +- src/sage/groups/matrix_gps/matrix_group.py | 4 +- src/sage/groups/pari_group.py | 2 +- src/sage/groups/perm_gps/cubegroup.py | 2 +- src/sage/groups/perm_gps/permgroup.py | 30 ++-- .../groups/perm_gps/permgroup_morphism.py | 4 +- src/sage/homology/cubical_complex.py | 20 +-- src/sage/homology/delta_complex.py | 16 +-- src/sage/homology/examples.py | 2 +- .../homology/simplicial_complex_homset.py | 4 +- .../homology/simplicial_complex_morphism.py | 2 +- src/sage/interacts/debugger.py | 2 +- src/sage/interacts/library.py | 2 +- src/sage/interfaces/axiom.py | 12 +- src/sage/interfaces/chomp.py | 14 +- src/sage/interfaces/expect.py | 40 +++--- src/sage/interfaces/gap.py | 12 +- src/sage/interfaces/gap3.py | 2 +- src/sage/interfaces/genus2reduction.py | 6 +- src/sage/interfaces/gfan.py | 2 +- src/sage/interfaces/giac.py | 14 +- src/sage/interfaces/gnuplot.py | 2 +- src/sage/interfaces/gp.py | 4 +- src/sage/interfaces/interface.py | 22 +-- src/sage/interfaces/kash.py | 4 +- src/sage/interfaces/lie.py | 8 +- src/sage/interfaces/lisp.py | 4 +- src/sage/interfaces/macaulay2.py | 12 +- src/sage/interfaces/magma.py | 16 +-- src/sage/interfaces/maple.py | 14 +- src/sage/interfaces/mathematica.py | 14 +- src/sage/interfaces/matlab.py | 4 +- src/sage/interfaces/maxima.py | 10 +- src/sage/interfaces/maxima_abstract.py | 12 +- src/sage/interfaces/maxima_lib.py | 12 +- src/sage/interfaces/mupad.py | 6 +- src/sage/interfaces/mwrank.py | 16 +-- src/sage/interfaces/octave.py | 4 +- src/sage/interfaces/phc.py | 18 +-- src/sage/interfaces/psage.py | 4 +- src/sage/interfaces/qepcad.py | 32 ++--- src/sage/interfaces/qsieve.py | 4 +- src/sage/interfaces/r.py | 12 +- src/sage/interfaces/rubik.py | 6 +- src/sage/interfaces/sage0.py | 2 +- src/sage/interfaces/scilab.py | 2 +- src/sage/interfaces/singular.py | 18 +-- src/sage/lfunctions/dokchitser.py | 16 +-- src/sage/lfunctions/lcalc.py | 2 +- src/sage/lfunctions/sympow.py | 16 +-- src/sage/libs/coxeter3/coxeter_group.py | 4 +- src/sage/libs/mwrank/interface.py | 16 +-- src/sage/libs/pari/gen_py.py | 4 +- src/sage/logic/logicparser.py | 4 +- src/sage/matrix/benchmark.py | 48 +++---- src/sage/matrix/berlekamp_massey.py | 4 +- src/sage/matrix/constructor.py | 24 ++-- .../matrix/matrix_integer_dense_saturation.py | 2 +- src/sage/matrix/symplectic_basis.py | 14 +- src/sage/media/wav.py | 8 +- src/sage/misc/benchmark.py | 2 +- src/sage/misc/cython.py | 8 +- src/sage/misc/edit_module.py | 8 +- src/sage/misc/explain_pickle.py | 10 +- src/sage/misc/functional.py | 4 +- src/sage/misc/misc.py | 16 +-- src/sage/misc/package.py | 6 +- src/sage/misc/preparser.py | 6 +- src/sage/misc/sage_eval.py | 2 +- src/sage/misc/sage_extension.py | 2 +- src/sage/misc/sage_input.py | 12 +- src/sage/misc/sage_itertools.py | 4 +- src/sage/misc/sagedoc.py | 10 +- src/sage/misc/sageinspect.py | 8 +- src/sage/misc/superseded.py | 2 +- src/sage/misc/trace.py | 2 +- src/sage/misc/unknown.py | 2 +- src/sage/misc/viewer.py | 4 +- src/sage/modular/abvar/abvar.py | 130 +++++++++--------- .../modular/abvar/abvar_ambient_jacobian.py | 4 +- src/sage/modular/abvar/abvar_newform.py | 2 +- src/sage/modular/abvar/constructor.py | 4 +- src/sage/modular/abvar/cuspidal_subgroup.py | 2 +- src/sage/modular/abvar/finite_subgroup.py | 24 ++-- src/sage/modular/abvar/homology.py | 10 +- src/sage/modular/abvar/homspace.py | 18 +-- src/sage/modular/abvar/lseries.py | 2 +- src/sage/modular/abvar/morphism.py | 12 +- src/sage/modular/abvar/torsion_subgroup.py | 6 +- .../modular/arithgroup/arithgroup_generic.py | 18 +-- .../modular/arithgroup/arithgroup_perm.py | 16 +-- src/sage/modular/arithgroup/congroup_gamma.py | 2 +- .../modular/arithgroup/congroup_gamma0.py | 2 +- .../modular/arithgroup/congroup_gamma1.py | 8 +- .../modular/arithgroup/congroup_gammaH.py | 14 +- .../modular/arithgroup/congroup_generic.py | 8 +- src/sage/modular/arithgroup/tests.py | 12 +- src/sage/modular/cusps.py | 22 +-- src/sage/modular/cusps_nf.py | 40 +++--- src/sage/modular/dims.py | 14 +- src/sage/modular/dirichlet.py | 45 +++--- src/sage/modular/etaproducts.py | 42 +++--- src/sage/modular/hecke/algebra.py | 8 +- src/sage/modular/hecke/ambient_module.py | 28 ++-- src/sage/modular/hecke/element.py | 2 +- src/sage/modular/hecke/hecke_operator.py | 14 +- src/sage/modular/hecke/homspace.py | 6 +- src/sage/modular/hecke/module.py | 45 +++--- src/sage/modular/hecke/morphism.py | 2 +- src/sage/modular/hecke/submodule.py | 34 ++--- src/sage/modular/local_comp/smoothchar.py | 4 +- src/sage/modular/modform/ambient.py | 8 +- src/sage/modular/modform/ambient_R.py | 2 +- src/sage/modular/modform/ambient_eps.py | 6 +- src/sage/modular/modform/constructor.py | 29 ++-- .../modular/modform/cuspidal_submodule.py | 2 +- src/sage/modular/modform/eis_series.py | 8 +- .../modular/modform/eisenstein_submodule.py | 4 +- src/sage/modular/modform/element.py | 42 +++--- src/sage/modular/modform/half_integral.py | 6 +- .../modular/modform/hecke_operator_on_qexp.py | 8 +- src/sage/modular/modform/j_invariant.py | 2 +- src/sage/modular/modform/numerical.py | 10 +- src/sage/modular/modform/space.py | 46 +++---- src/sage/modular/modform/theta.py | 4 +- src/sage/modular/modform/vm_basis.py | 4 +- src/sage/modular/modsym/boundary.py | 30 ++-- src/sage/modular/modsym/element.py | 8 +- src/sage/modular/modsym/hecke_operator.py | 2 +- src/sage/modular/modsym/manin_symbols.py | 20 +-- src/sage/modular/modsym/modsym.py | 10 +- src/sage/modular/modsym/p1list_nf.py | 24 ++-- src/sage/modular/modsym/relation_matrix.py | 6 +- src/sage/modular/modsym/space.py | 74 +++++----- src/sage/modular/modsym/subspace.py | 4 +- src/sage/modular/modsym/tests.py | 4 +- src/sage/modular/overconvergent/genus0.py | 54 ++++---- .../modular/overconvergent/hecke_series.py | 10 +- .../modular/overconvergent/weightspace.py | 16 +-- src/sage/modular/quatalg/brandt.py | 34 ++--- src/sage/modular/ssmod/ssmod.py | 18 +-- src/sage/modules/fg_pid/fgp_module.py | 34 ++--- src/sage/modules/fg_pid/fgp_morphism.py | 14 +- src/sage/modules/free_module.py | 106 +++++++------- src/sage/modules/free_module_homspace.py | 2 +- src/sage/modules/free_module_morphism.py | 20 +-- src/sage/modules/free_quadratic_module.py | 14 +- src/sage/modules/matrix_morphism.py | 22 +-- src/sage/modules/vector_space_morphism.py | 2 +- src/sage/monoids/free_abelian_monoid.py | 6 +- .../monoids/free_abelian_monoid_element.py | 11 +- src/sage/monoids/free_monoid.py | 6 +- src/sage/monoids/free_monoid_element.py | 12 +- src/sage/monoids/string_ops.py | 14 +- src/sage/numerical/knapsack.py | 28 ++-- src/sage/parallel/decorate.py | 2 +- src/sage/parallel/use_fork.py | 2 +- src/sage/plot/animate.py | 6 +- src/sage/plot/arc.py | 4 +- src/sage/plot/bezier_path.py | 2 +- src/sage/plot/circle.py | 2 +- src/sage/plot/contour_plot.py | 2 +- src/sage/plot/disk.py | 2 +- src/sage/plot/ellipse.py | 4 +- src/sage/plot/graphics.py | 16 +-- src/sage/plot/matrix_plot.py | 8 +- src/sage/plot/misc.py | 8 +- src/sage/plot/plot.py | 12 +- src/sage/plot/plot3d/list_plot3d.py | 6 +- src/sage/plot/plot3d/parametric_plot3d.py | 2 +- src/sage/plot/plot3d/plot3d.py | 12 +- src/sage/plot/plot3d/revolution_plot3d.py | 2 +- src/sage/plot/plot3d/shapes2.py | 6 +- src/sage/plot/plot3d/tachyon.py | 2 +- src/sage/plot/plot3d/tri_plot.py | 2 +- src/sage/plot/point.py | 4 +- src/sage/plot/polygon.py | 2 +- src/sage/plot/primitive.py | 2 +- src/sage/plot/text.py | 2 +- src/sage/probability/random_variable.py | 27 ++-- src/sage/quadratic_forms/binary_qf.py | 16 +-- src/sage/quadratic_forms/constructions.py | 6 +- src/sage/quadratic_forms/extras.py | 6 +- src/sage/quadratic_forms/genera/genus.py | 10 +- src/sage/quadratic_forms/qfsolve.py | 2 +- src/sage/quadratic_forms/quadratic_form.py | 50 +++---- .../quadratic_form__automorphisms.py | 6 +- .../quadratic_form__equivalence_testing.py | 18 +-- .../quadratic_forms/quadratic_form__genus.py | 10 +- ...uadratic_form__local_density_congruence.py | 30 ++-- ...uadratic_form__local_density_interfaces.py | 4 +- .../quadratic_form__local_field_invariants.py | 6 +- .../quadratic_form__local_normal_form.py | 18 +-- ...c_form__local_representation_conditions.py | 8 +- ...dratic_form__mass__Conway_Sloane_masses.py | 10 +- .../quadratic_form__mass__Siegel_densities.py | 6 +- .../quadratic_form__neighbors.py | 4 +- .../quadratic_form__reduction_theory.py | 8 +- .../quadratic_form__split_local_covering.py | 8 +- .../quadratic_form__ternary_Tornaria.py | 8 +- .../quadratic_forms/quadratic_form__theta.py | 16 +-- .../quadratic_form__variable_substitutions.py | 4 +- .../quadratic_forms/random_quadraticform.py | 4 +- src/sage/quadratic_forms/ternary_qf.py | 20 +-- src/sage/rings/arith.py | 81 ++++++----- src/sage/rings/big_oh.py | 10 +- src/sage/rings/complex_field.py | 2 +- src/sage/rings/complex_interval_field.py | 2 +- src/sage/rings/contfrac.py | 16 +-- .../rings/finite_rings/conway_polynomials.py | 2 +- .../rings/finite_rings/element_ext_pari.py | 30 ++-- .../finite_rings/finite_field_ext_pari.py | 16 +-- .../rings/finite_rings/finite_field_givaro.py | 12 +- .../finite_rings/finite_field_prime_modn.py | 4 +- src/sage/rings/finite_rings/homset.py | 2 +- src/sage/rings/fraction_field.py | 4 +- .../rings/function_field/function_field.py | 22 +-- .../function_field/function_field_ideal.py | 4 +- .../function_field/function_field_order.py | 14 +- src/sage/rings/function_field/maps.py | 2 +- src/sage/rings/homset.py | 4 +- src/sage/rings/ideal.py | 18 +-- src/sage/rings/infinity.py | 36 ++--- src/sage/rings/laurent_series_ring.py | 10 +- src/sage/rings/misc.py | 2 +- src/sage/rings/monomials.py | 2 +- src/sage/rings/number_field/galois_group.py | 28 ++-- src/sage/rings/number_field/morphism.py | 18 +-- src/sage/rings/number_field/number_field.py | 94 ++++++------- .../rings/number_field/number_field_ideal.py | 58 ++++---- .../number_field/number_field_ideal_rel.py | 22 +-- .../rings/number_field/number_field_rel.py | 40 +++--- src/sage/rings/number_field/order.py | 50 +++---- .../rings/number_field/totallyreal_phc.py | 2 +- .../rings/number_field/totallyreal_rel.py | 12 +- src/sage/rings/number_field/unit_group.py | 10 +- .../padics/eisenstein_extension_generic.py | 2 +- src/sage/rings/padics/factory.py | 40 +++--- src/sage/rings/padics/generic_nodes.py | 6 +- src/sage/rings/padics/local_generic.py | 2 +- src/sage/rings/padics/padic_base_generic.py | 6 +- src/sage/rings/padics/padic_base_leaves.py | 4 +- src/sage/rings/padics/padic_generic.py | 2 +- .../padics/unramified_extension_generic.py | 2 +- src/sage/rings/pari_ring.py | 2 +- src/sage/rings/polynomial/convolution.py | 2 +- src/sage/rings/polynomial/groebner_fan.py | 18 +-- src/sage/rings/polynomial/ideal.py | 4 +- .../polynomial/infinite_polynomial_element.py | 4 +- .../polynomial/infinite_polynomial_ring.py | 56 ++++---- .../polynomial/laurent_polynomial_ring.py | 24 ++-- .../polynomial/multi_polynomial_element.py | 26 ++-- .../polynomial/multi_polynomial_ideal.py | 42 +++--- .../rings/polynomial/multi_polynomial_ring.py | 12 +- .../polynomial_padic_capped_relative_dense.py | 18 +-- .../padics/polynomial_padic_flat.py | 2 +- .../polynomial/polynomial_element_generic.py | 4 +- .../polynomial/polynomial_quotient_ring.py | 22 +-- .../polynomial_quotient_ring_element.py | 12 +- src/sage/rings/polynomial/polynomial_ring.py | 36 ++--- .../polynomial_singular_interface.py | 4 +- src/sage/rings/polynomial/symmetric_ideal.py | 2 +- src/sage/rings/polynomial/term_order.py | 24 ++-- src/sage/rings/polynomial/toy_variety.py | 6 +- src/sage/rings/power_series_ring.py | 16 +-- src/sage/rings/qqbar.py | 6 +- src/sage/rings/quotient_ring.py | 12 +- src/sage/rings/rational_field.py | 8 +- src/sage/sandpiles/sandpile.py | 18 +-- src/sage/schemes/affine/affine_homset.py | 4 +- src/sage/schemes/elliptic_curves/cm.py | 10 +- .../schemes/elliptic_curves/constructor.py | 12 +- .../elliptic_curves/ell_curve_isogeny.py | 52 +++---- src/sage/schemes/elliptic_curves/ell_egros.py | 2 +- src/sage/schemes/elliptic_curves/ell_field.py | 58 ++++---- .../elliptic_curves/ell_finite_field.py | 24 ++-- .../schemes/elliptic_curves/ell_generic.py | 23 ++-- .../schemes/elliptic_curves/ell_local_data.py | 42 +++--- .../elliptic_curves/ell_modular_symbols.py | 18 +-- .../elliptic_curves/ell_number_field.py | 16 +-- .../elliptic_curves/ell_padic_field.py | 2 +- .../elliptic_curves/ell_rational_field.py | 104 +++++++------- .../schemes/elliptic_curves/ell_tate_curve.py | 24 ++-- .../schemes/elliptic_curves/formal_group.py | 2 +- .../elliptic_curves/gal_reps_number_field.py | 4 +- .../schemes/elliptic_curves/isogeny_class.py | 2 +- .../elliptic_curves/isogeny_small_degree.py | 2 +- .../schemes/elliptic_curves/kodaira_symbol.py | 6 +- .../modular_parametrization.py | 4 +- .../schemes/elliptic_curves/padic_lseries.py | 44 +++--- src/sage/schemes/elliptic_curves/padics.py | 56 ++++---- .../schemes/elliptic_curves/period_lattice.py | 18 +-- .../elliptic_curves/weierstrass_morphism.py | 20 +-- src/sage/schemes/generic/algebraic_scheme.py | 48 ++++--- src/sage/schemes/generic/ambient_space.py | 6 +- src/sage/schemes/generic/divisor.py | 11 +- src/sage/schemes/generic/glue.py | 6 +- src/sage/schemes/generic/homset.py | 2 +- src/sage/schemes/generic/hypersurface.py | 7 +- src/sage/schemes/generic/morphism.py | 16 +-- src/sage/schemes/generic/point.py | 2 +- src/sage/schemes/generic/scheme.py | 8 +- src/sage/schemes/generic/spec.py | 6 +- .../hyperelliptic_curves/constructor.py | 19 ++- .../hyperelliptic_finite_field.py | 10 +- .../hyperelliptic_g2_generic.py | 3 +- .../hyperelliptic_generic.py | 10 +- .../hyperelliptic_padic_field.py | 10 +- .../hyperelliptic_curves/invariants.py | 2 +- .../hyperelliptic_curves/jacobian_generic.py | 2 +- .../hyperelliptic_curves/jacobian_homset.py | 8 +- .../hyperelliptic_curves/jacobian_morphism.py | 5 +- .../schemes/jacobians/abstract_jacobian.py | 6 +- src/sage/schemes/plane_conics/con_field.py | 36 ++--- .../schemes/plane_conics/con_number_field.py | 20 +-- .../plane_conics/con_rational_field.py | 6 +- src/sage/schemes/plane_conics/constructor.py | 36 ++--- src/sage/schemes/plane_curves/affine_curve.py | 12 +- src/sage/schemes/plane_curves/constructor.py | 10 +- .../schemes/plane_curves/projective_curve.py | 18 +-- .../schemes/projective/projective_homset.py | 8 +- .../schemes/projective/projective_point.py | 2 +- src/sage/schemes/toric/chow_group.py | 14 +- src/sage/schemes/toric/divisor.py | 2 +- src/sage/schemes/toric/homset.py | 2 +- src/sage/schemes/toric/ideal.py | 2 +- src/sage/schemes/toric/variety.py | 6 +- src/sage/server/trac/trac.py | 2 +- src/sage/sets/integer_range.py | 10 +- src/sage/sets/non_negative_integers.py | 2 +- src/sage/sets/set.py | 14 +- src/sage/stats/basic_stats.py | 2 +- src/sage/stats/r.py | 2 +- src/sage/structure/factorization.py | 30 ++-- src/sage/structure/formal_sum.py | 2 +- src/sage/structure/gens_py.py | 4 +- src/sage/structure/list_clone_timings.py | 2 +- src/sage/symbolic/assumptions.py | 8 +- src/sage/symbolic/callable.py | 4 +- src/sage/symbolic/constants.py | 6 +- src/sage/symbolic/expression_conversions.py | 30 ++-- src/sage/symbolic/function_factory.py | 4 +- src/sage/symbolic/integration/external.py | 4 +- src/sage/symbolic/integration/integral.py | 2 +- src/sage/symbolic/random_tests.py | 8 +- src/sage/symbolic/relation.py | 12 +- src/sage/symbolic/units.py | 8 +- src/sage/tensor/coordinate_patch.py | 6 +- src/sage/tensor/differential_form_element.py | 53 ++++--- src/sage/tensor/differential_forms.py | 6 +- src/setup.py | 5 +- 504 files changed, 3169 insertions(+), 3205 deletions(-) diff --git a/src/bin/sage-num-threads.py b/src/bin/sage-num-threads.py index e9f0cc379fc..09f99a612c5 100755 --- a/src/bin/sage-num-threads.py +++ b/src/bin/sage-num-threads.py @@ -75,14 +75,14 @@ def parse_jobs_from_MAKE(MAKE, unlimited=999999): (j,num) = re.subn(r'^(.* )?(-j *|--jobs(=(?=[0-9])| +))([0-9]*)( .*?)?$', r'\4', MAKE, count=1) if num < 1: # No replacement done, i.e. no -j option found - raise KeyError, "No number of jobs specified" + raise KeyError("No number of jobs specified") elif j == "": # j is empty: unlimited number of jobs! :-) j = unlimited else: j = int(j) if j <= 0: - raise ValueError, "Non-positive value specified for -j" + raise ValueError("Non-positive value specified for -j") # Next, find the value of -l # If it is specified, use this as an upper bound on j diff --git a/src/doc/common/inventory_builder.py b/src/doc/common/inventory_builder.py index d2f5e38c234..5a98ad8649e 100644 --- a/src/doc/common/inventory_builder.py +++ b/src/doc/common/inventory_builder.py @@ -97,7 +97,7 @@ def removed_method_error(self): This is just for making sure that some writer methods are indeed deactivated. """ - raise RuntimeError, "This function shouldn't be called in \"%s\" builder"%(self.name) + raise RuntimeError("This function shouldn't be called in \"%s\" builder"%(self.name)) copy_image_files = removed_method_error copy_download_files = removed_method_error diff --git a/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra.py b/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra.py index 4c306eebdaf..9acc8cba623 100644 --- a/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra.py +++ b/src/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra.py @@ -633,7 +633,7 @@ def maximal_ideal(self): ValueError: algebra is not local """ if self.degree() == 0: - raise ValueError, "the zero algebra is not local" + raise ValueError("the zero algebra is not local") if not(self.is_unitary() and self.is_commutative() and (self._assume_associative or self.is_associative())): raise TypeError("algebra must be unitary, commutative and associative") diff --git a/src/sage/algebras/free_algebra.py b/src/sage/algebras/free_algebra.py index 17b68110ffc..dc90de6f92e 100644 --- a/src/sage/algebras/free_algebra.py +++ b/src/sage/algebras/free_algebra.py @@ -274,7 +274,7 @@ def create_key(self,base_ring, arg1=None, arg2=None, else: raise TypeError except (TypeError, NotImplementedError) as msg: - raise NotImplementedError, "The letterplace implementation is not available for the free algebra you requested" + raise NotImplementedError("The letterplace implementation is not available for the free algebra you requested") if PolRing is not None: if degrees is None: return (PolRing,) diff --git a/src/sage/algebras/quatalg/quaternion_algebra.py b/src/sage/algebras/quatalg/quaternion_algebra.py index 5db9783ceb6..b9d0d34992f 100644 --- a/src/sage/algebras/quatalg/quaternion_algebra.py +++ b/src/sage/algebras/quatalg/quaternion_algebra.py @@ -1321,7 +1321,7 @@ def __init__(self, A, basis, check=True): # has rank 4 V = A.base_ring()**4 if V.span([ V(x.coefficient_tuple()) for x in basis]).dimension() != 4: - raise ValueError, "basis must have rank 4" + raise ValueError("basis must have rank 4") # The additional checks will work over QQ and over number fields, # but we can't actually do much with an order defined over a number @@ -1332,13 +1332,13 @@ def __init__(self, A, basis, check=True): v = M.solve_left(V([1,0,0,0])) if v.denominator() != 1: - raise ValueError, "lattice must contain 1" + raise ValueError("lattice must contain 1") # check if multiplicatively closed M1 = basis_for_quaternion_lattice(basis) M2 = basis_for_quaternion_lattice(list(basis) + [ x*y for x in basis for y in basis]) if M1 != M2: - raise ValueError, "given lattice must be a ring" + raise ValueError("given lattice must be a ring") if A.base_ring() != QQ: # slow code over number fields (should eventually use PARI's nfhnf) O = None @@ -1352,13 +1352,13 @@ def __init__(self, A, basis, check=True): v = M.solve_left(V([1,0,0,0])) if any([ not a in O for a in v]): - raise ValueError, "lattice must contain 1" + raise ValueError("lattice must contain 1") # check if multiplicatively closed Y = matrix(QQ, 16, 4, [ (x*y).coefficient_tuple() for x in basis for y in basis]) X = M.solve_left(Y) if any([ not a in O for x in X for a in x ]): - raise ValueError, "given lattice must be a ring" + raise ValueError("given lattice must be a ring") self.__basis = basis self.__quaternion_algebra = A @@ -2857,15 +2857,15 @@ def maxord_solve_aux_eq(a, b, p): ... assert mod(1 - a*y^2 - b*z^2 + a*b*w^2, 4) == 0 """ if p != ZZ(2): - raise NotImplementedError, "Algorithm only implemented over ZZ at the moment" + raise NotImplementedError("Algorithm only implemented over ZZ at the moment") v_a = a.valuation(p) v_b = b.valuation(p) if v_a != 0: - raise RuntimeError, "a must have v_p(a)=0" + raise RuntimeError("a must have v_p(a)=0") if v_b != 0 and v_b != 1: - raise RuntimeError, "b must have v_p(b) in {0,1}" + raise RuntimeError("b must have v_p(b) in {0,1}") R = ZZ.quo(ZZ(4)) lut = { diff --git a/src/sage/algebras/steenrod/steenrod_algebra.py b/src/sage/algebras/steenrod/steenrod_algebra.py index 2dee9c80c18..fd1c74e9cea 100644 --- a/src/sage/algebras/steenrod/steenrod_algebra.py +++ b/src/sage/algebras/steenrod/steenrod_algebra.py @@ -2895,7 +2895,7 @@ def top_class(self): True """ if not self.is_finite(): - raise ValueError, "the algebra is not finite dimensional" + raise ValueError("the algebra is not finite dimensional") p = self.prime() # we create the top class in the Milnor basis version AM = SteenrodAlgebra(basis='milnor', p=p) diff --git a/src/sage/categories/affine_weyl_groups.py b/src/sage/categories/affine_weyl_groups.py index eb9627d760f..c1913bf3348 100644 --- a/src/sage/categories/affine_weyl_groups.py +++ b/src/sage/categories/affine_weyl_groups.py @@ -158,7 +158,7 @@ def affine_grassmannian_to_core(self): from sage.combinat.partition import Partition from sage.combinat.core import Core if not self.is_affine_grassmannian() or not self.parent().cartan_type().letter == 'A': - raise ValueError, "Error! this only works on type 'A' affine Grassmannian elements" + raise ValueError("Error! this only works on type 'A' affine Grassmannian elements") out = Partition([]) rword = self.reduced_word() kp1 = self.parent().n diff --git a/src/sage/categories/algebra_ideals.py b/src/sage/categories/algebra_ideals.py index 236ca6a61f9..8a022712012 100644 --- a/src/sage/categories/algebra_ideals.py +++ b/src/sage/categories/algebra_ideals.py @@ -48,7 +48,7 @@ def __init__(self, A): """ from sage.algebras.algebra import is_Algebra if not is_Algebra(A): # A not in Algebras() ? - raise TypeError, "A (=%s) must be an algebra"%A + raise TypeError("A (=%s) must be an algebra"%A) Category_ideal.__init__(self, A) def algebra(self): diff --git a/src/sage/categories/algebra_modules.py b/src/sage/categories/algebra_modules.py index c7785b6619c..518acfbaf83 100644 --- a/src/sage/categories/algebra_modules.py +++ b/src/sage/categories/algebra_modules.py @@ -53,7 +53,7 @@ def __init__(self, A): """ from sage.categories.commutative_algebras import CommutativeAlgebras if not hasattr(A, "base_ring") or not A in CommutativeAlgebras(A.base_ring()): - raise TypeError, "A (=%s) must be a commutative algebra"%A + raise TypeError("A (=%s) must be a commutative algebra"%A) Category_module.__init__(self, A) @classmethod diff --git a/src/sage/categories/algebras_with_basis.py b/src/sage/categories/algebras_with_basis.py index ccd813a6fcd..e644d0fcff2 100644 --- a/src/sage/categories/algebras_with_basis.py +++ b/src/sage/categories/algebras_with_basis.py @@ -410,7 +410,7 @@ def __invert__(self): if len(mcs) == 1 and one in mcs: return self.parent()( ~mcs[ one ] ) else: - raise ValueError, "cannot invert self (= %s)"%self + raise ValueError("cannot invert self (= %s)"%self) class CartesianProducts(CartesianProductsCategory): diff --git a/src/sage/categories/category.py b/src/sage/categories/category.py index b90b56f4676..cbc4ce91098 100644 --- a/src/sage/categories/category.py +++ b/src/sage/categories/category.py @@ -494,7 +494,7 @@ def __init__(self, s=None): self._label = s self.__repr_object_names = s else: - raise TypeError, "Argument string must be a string." + raise TypeError("Argument string must be a string.") self.__class__ = dynamic_class("%s_with_category"%self.__class__.__name__, (self.__class__, self.subcategory_class, ), cache = False, reduction = None, @@ -1545,7 +1545,7 @@ def meet(categories): """ categories = tuple(categories) if len(categories) == 0: - raise ValueError, "The meet of an empty list of categories is not implemented" + raise ValueError("The meet of an empty list of categories is not implemented") result = categories[0] for category in categories[1:]: result = result._meet_(category) @@ -1894,7 +1894,7 @@ def base(self): for C in self._all_super_categories_proper: if isinstance(C,Category_over_base): return C.base() - raise AttributeError, "This hom category has no base" + raise AttributeError("This hom category has no base") def super_categories(self): """ diff --git a/src/sage/categories/classical_crystals.py b/src/sage/categories/classical_crystals.py index 404ff61f938..3c852454518 100644 --- a/src/sage/categories/classical_crystals.py +++ b/src/sage/categories/classical_crystals.py @@ -250,7 +250,7 @@ def character(self, R=None): if R == None: R = WeylCharacterRing(self.cartan_type()) if not R.cartan_type() == self.cartan_type(): - raise ValueError, "Weyl character ring does not have the right Cartan type" + raise ValueError("Weyl character ring does not have the right Cartan type") assert R.basis().keys() == self.weight_lattice_realization() return R.sum_of_monomials( x.weight() for x in self.highest_weight_vectors() ) diff --git a/src/sage/categories/commutative_algebra_ideals.py b/src/sage/categories/commutative_algebra_ideals.py index a196bbfa9c4..c7924e7afc4 100644 --- a/src/sage/categories/commutative_algebra_ideals.py +++ b/src/sage/categories/commutative_algebra_ideals.py @@ -55,7 +55,7 @@ def __init__(self, A): from sage.algebras.algebra import is_Algebra from sage.rings.commutative_ring import is_CommutativeRing if not (is_Algebra(A) and is_CommutativeRing(A)): - raise TypeError, "A (=%s) must be a commutative algebra"%A + raise TypeError("A (=%s) must be a commutative algebra"%A) Category_in_ambient.__init__(self, A) def algebra(self): diff --git a/src/sage/categories/commutative_ring_ideals.py b/src/sage/categories/commutative_ring_ideals.py index 2409191259c..948c30eeba1 100644 --- a/src/sage/categories/commutative_ring_ideals.py +++ b/src/sage/categories/commutative_ring_ideals.py @@ -43,7 +43,7 @@ def __init__(self, R): sage: TestSuite(CommutativeRingIdeals(ZZ)).run() """ if R not in CommutativeRings(): - raise TypeError, "R (=%s) must be a commutative ring"%R + raise TypeError("R (=%s) must be a commutative ring"%R) Category_ideal.__init__(self, R) def super_categories(self): diff --git a/src/sage/categories/coxeter_groups.py b/src/sage/categories/coxeter_groups.py index 19851189ee2..18bc1390ceb 100644 --- a/src/sage/categories/coxeter_groups.py +++ b/src/sage/categories/coxeter_groups.py @@ -386,7 +386,7 @@ def simple_reflection(self, i): """ if not i in self.index_set(): - raise ValueError, "%s is not in the Dynkin node set %s"%(i,self.index_set()) + raise ValueError("%s is not in the Dynkin node set %s"%(i,self.index_set())) return self.one().apply_simple_reflection(i) # don't care about left/right @cached_method @@ -487,7 +487,7 @@ def simple_projection(self, i, side = 'right', length_increasing = True, toward_ """ if not (i in self.index_set() or i == 0): - raise ValueError, "%s is not 0 and not in the Dynkin node set %s"%(i, self.index_set()) + raise ValueError("%s is not 0 and not in the Dynkin node set %s"%(i, self.index_set())) if toward_max is not None: deprecation("the toward_max option of CoxeterGroups.ParentMethods.simple_projection is deprecated; please use length_increasing instead", 'Sage Version 5.0') length_increasing = toward_max @@ -723,11 +723,11 @@ def has_descent(self, i, side = 'right', positive=False): :meth:`.has_left_descent` and :meth:`.has_right_descent`. """ if not isinstance(positive, bool): - raise TypeError, "%s is not a boolean"%(bool) + raise TypeError("%s is not a boolean"%(bool)) if side == 'right': return self.has_right_descent(i) != positive if side != 'left': - raise ValueError, "%s is neither 'right' nor 'left'"%(side) + raise ValueError("%s is neither 'right' nor 'left'"%(side)) return self.has_left_descent(i) != positive # @abstract_method(optional = True) @@ -1657,7 +1657,7 @@ def bruhat_le(self, other): """ if not have_same_parent(self, other): - raise TypeError, "%s and %s do not have the same parent"%(self, other) + raise TypeError("%s and %s do not have the same parent"%(self, other)) # could first compare the length, when that information is cheap desc = other.first_descent() if desc is not None: @@ -1721,7 +1721,7 @@ def weak_le(self, other, side = 'right'): ... assert u.permutohedron_lequal(v, side='left') == P4toW(u).weak_le(P4toW(v), side='left') """ if not have_same_parent(self, other): - raise TypeError, "%s and %s do not have the same parent"%(self,other) + raise TypeError("%s and %s do not have the same parent"%(self,other)) # could first compare the length, when that information is cheap prefix_side = 'left' if side == 'right' else 'right' @@ -1821,10 +1821,10 @@ def apply_demazure_product(self, element, side = 'right', length_increasing = Tr if isinstance(element, (tuple)): element = [x for x in element] if not isinstance(element, (list)): - raise TypeError, "Bad Coxeter group element input: %s"%(element) + raise TypeError("Bad Coxeter group element input: %s"%(element)) I = self.parent().index_set() if not all(i in I for i in element): - raise ValueError, "%s does not have all its members in the index set of the %s"%(element, self.parent()) + raise ValueError("%s does not have all its members in the index set of the %s"%(element, self.parent())) # the copy is so that if we need to reverse the list, the original will not # get reversed the_word = copy(element) @@ -1862,10 +1862,10 @@ def min_demazure_product_greater(self, element): # else require that ``element`` is a list or tuple of index_set elements else: if not isinstance(element, (tuple,list)): - raise TypeError, "Bad Coxeter group element input: %s"%(element) + raise TypeError("Bad Coxeter group element input: %s"%(element)) I = self.parent().index_set() if not all(i in I for i in element): - raise ValueError, "%s does not have all its members in the index set of the %s"%(element, self.parent()) + raise ValueError("%s does not have all its members in the index set of the %s"%(element, self.parent())) the_word = element for i in the_word: if self.has_descent(i, side = 'left'): @@ -1911,11 +1911,11 @@ def deodhar_factor_element(self, w, index_set): """ if self != self.coset_representative(index_set): - raise ValueError, "%s is not of minimum length in its coset for the parabolic subgroup with index set %s"%(self.reduced_word(),index_set) + raise ValueError("%s is not of minimum length in its coset for the parabolic subgroup with index set %s"%(self.reduced_word(),index_set)) if w != w.coset_representative(index_set): - raise ValueError, "%s is not of minimum length in its coset for the parabolic subgroup with index set %s"%(w.reduced_word(),index_set) + raise ValueError("%s is not of minimum length in its coset for the parabolic subgroup with index set %s"%(w.reduced_word(),index_set)) if not self.bruhat_le(w): - raise ValueError, "Must have %s <= %s"%(self.reduced_word(), w.reduced_word()) + raise ValueError("Must have %s <= %s"%(self.reduced_word(), w.reduced_word())) if w.is_one(): return w i = w.first_descent(side = 'left') @@ -1960,7 +1960,7 @@ def deodhar_lift_up(self, w, index_set): vmin = self.coset_representative(index_set) wmin = w.coset_representative(index_set) if not vmin.bruhat_le(wmin): - raise ValueError, "Must have %s <= %s mod the parabolic subgroup with index set %s"%(self.reduced_word(), w.reduced_word(), index_set) + raise ValueError("Must have %s <= %s mod the parabolic subgroup with index set %s"%(self.reduced_word(), w.reduced_word(), index_set)) vJ = vmin.inverse() * self dsp = vmin.deodhar_factor_element(wmin,index_set) return wmin * vJ.min_demazure_product_greater(dsp) @@ -1996,7 +1996,7 @@ def deodhar_lift_down(self, w, index_set): vmin = self.coset_representative(index_set) wmin = w.coset_representative(index_set) if not wmin.bruhat_le(vmin): - raise ValueError, "Must have %s <= %s mod the parabolic subgroup with index set %s"%(w.reduced_word(), self.reduced_word(), index_set) + raise ValueError("Must have %s <= %s mod the parabolic subgroup with index set %s"%(w.reduced_word(), self.reduced_word(), index_set)) vJ = vmin.inverse() * self dsp = wmin.deodhar_factor_element(vmin,index_set) diff --git a/src/sage/categories/crystals.py b/src/sage/categories/crystals.py index 8858b2215b3..c2935f30ccb 100644 --- a/src/sage/categories/crystals.py +++ b/src/sage/categories/crystals.py @@ -427,7 +427,7 @@ def morphism(b): if d is not None: return d else: - raise ValueError, "This is not a morphism!" + raise ValueError("This is not a morphism!") #now we know that b is hw return g(b) @@ -448,7 +448,7 @@ def morphism(b): eigx = getattr(morphism[x], f_string)([automorphism(i) for k in range(similarity_factor[i])]) if bool(eix is None) != bool(eigx is None): # This is not a crystal morphism! - raise ValueError, "This is not a morphism!" #, print("x="x,"g(x)="g(x),"i="i) + raise ValueError("This is not a morphism!") #, print("x="x,"g(x)="g(x),"i="i) if (eix is not None) and (eix not in known): todo.add(eix) known.add(eix) @@ -1158,7 +1158,7 @@ def to_lowest_weight(self, index_set = None): from sage.categories.highest_weight_crystals import HighestWeightCrystals if index_set is None: if HighestWeightCrystals() not in self.parent().categories(): - raise ValueError, "This is not a highest weight crystals!" + raise ValueError("This is not a highest weight crystals!") index_set = self.index_set() for i in index_set: next = self.f(i) diff --git a/src/sage/categories/enumerated_sets.py b/src/sage/categories/enumerated_sets.py index 3384a31a3b1..4903a06dc6c 100644 --- a/src/sage/categories/enumerated_sets.py +++ b/src/sage/categories/enumerated_sets.py @@ -213,7 +213,7 @@ def __iter__(self): elif self.list != self._list_default: return self._iterator_from_list() else: - raise NotImplementedError, "iterator called but not implemented" + raise NotImplementedError("iterator called but not implemented") def cardinality(self): """ @@ -237,7 +237,7 @@ def cardinality(self): ... NotImplementedError: unknown cardinality """ - raise NotImplementedError, "unknown cardinality" + raise NotImplementedError("unknown cardinality") def list(self): """ @@ -254,7 +254,7 @@ def list(self): ... NotImplementedError: unknown cardinality """ - raise NotImplementedError, "unknown cardinality" + raise NotImplementedError("unknown cardinality") _list_default = list # needed by the check system. @@ -334,7 +334,7 @@ def _unrank_from_iterator(self, r): if counter == r: return u counter += 1 - raise ValueError, "the value must be between %s and %s inclusive"%(0,counter-1) + raise ValueError("the value must be between %s and %s inclusive"%(0,counter-1)) unrank = _unrank_from_iterator def _rank_from_iterator(self, x): @@ -542,7 +542,7 @@ def random_element(self): ... NotImplementedError: unknown cardinality """ - raise NotImplementedError, "unknown cardinality" + raise NotImplementedError("unknown cardinality") def map(self, f, name=None): r""" diff --git a/src/sage/categories/examples/facade_sets.py b/src/sage/categories/examples/facade_sets.py index 76497af998a..4355108803d 100644 --- a/src/sage/categories/examples/facade_sets.py +++ b/src/sage/categories/examples/facade_sets.py @@ -114,7 +114,7 @@ def _element_constructor_(self, object): if object > ZZ(0): return object else: - raise ValueError, "%s should be positive" + raise ValueError("%s should be positive") class IntegersCompletion(UniqueRepresentation, Parent): r""" diff --git a/src/sage/categories/examples/infinite_enumerated_sets.py b/src/sage/categories/examples/infinite_enumerated_sets.py index 1e4749b07c4..c3c15f17cec 100644 --- a/src/sage/categories/examples/infinite_enumerated_sets.py +++ b/src/sage/categories/examples/infinite_enumerated_sets.py @@ -137,7 +137,7 @@ def __call__(self, elt): if elt in self: return self._element_constructor_(elt) else: - raise ValueError, "Value %s is not a non negative integer."%(elt) + raise ValueError("Value %s is not a non negative integer."%(elt)) def an_element(self): """ diff --git a/src/sage/categories/examples/sets_cat.py b/src/sage/categories/examples/sets_cat.py index 021669d9167..ef9fdd6d180 100644 --- a/src/sage/categories/examples/sets_cat.py +++ b/src/sage/categories/examples/sets_cat.py @@ -211,7 +211,7 @@ def _element_constructor_(self, i): if i in self: return self._from_integer_(i) else: - raise ValueError, "%s is not a prime number"%(i) + raise ValueError("%s is not a prime number"%(i)) @abstract_method def _from_integer_(self, i): diff --git a/src/sage/categories/facade_sets.py b/src/sage/categories/facade_sets.py index 647cbf34ec2..4794f361c7f 100644 --- a/src/sage/categories/facade_sets.py +++ b/src/sage/categories/facade_sets.py @@ -146,7 +146,7 @@ def example(self, choice='subset'): elif choice == 'subset': return examples.PositiveIntegerMonoid() else: - raise TypeError, "choice should be 'union' or 'subset'" + raise TypeError("choice should be 'union' or 'subset'") class ParentMethods: @@ -208,7 +208,7 @@ def _element_constructor_(self, element): return parent(element) except Exception: pass - raise ValueError, "Can't coerce `%s` in any parent `%s` is a facade for"%(element, self) + raise ValueError("Can't coerce `%s` in any parent `%s` is a facade for"%(element, self)) def facade_for(self): """ diff --git a/src/sage/categories/fields.py b/src/sage/categories/fields.py index e1547f6a724..ba447eb030b 100644 --- a/src/sage/categories/fields.py +++ b/src/sage/categories/fields.py @@ -161,7 +161,7 @@ def _call_(self, x): try: return x.fraction_field() except AttributeError: - raise TypeError, "unable to associate a field to %s"%x + raise TypeError("unable to associate a field to %s"%x) class ParentMethods: def is_field(self): @@ -333,7 +333,7 @@ def gcd(self,other): try: other = P(other) except (TypeError, ValueError): - raise ArithmeticError, "The second argument can not be interpreted in the parent of the first argument. Can't compute the gcd" + raise ArithmeticError("The second argument can not be interpreted in the parent of the first argument. Can't compute the gcd") from sage.rings.integer_ring import ZZ if ZZ.is_subring(P): try: @@ -388,7 +388,7 @@ def lcm(self,other): try: other = P(other) except (TypeError, ValueError): - raise ArithmeticError, "The second argument can not be interpreted in the parent of the first argument. Can't compute the lcm" + raise ArithmeticError("The second argument can not be interpreted in the parent of the first argument. Can't compute the lcm") from sage.rings.integer_ring import ZZ if ZZ.is_subring(P): try: diff --git a/src/sage/categories/finite_enumerated_sets.py b/src/sage/categories/finite_enumerated_sets.py index 30c8424ca04..ab3030b0de0 100644 --- a/src/sage/categories/finite_enumerated_sets.py +++ b/src/sage/categories/finite_enumerated_sets.py @@ -248,7 +248,7 @@ def _unrank_from_list(self, r): try: return lst[r] except IndexError: - raise ValueError, "the value must be between %s and %s inclusive"%(0,len(lst)-1) + raise ValueError("the value must be between %s and %s inclusive"%(0,len(lst)-1)) def list(self): diff --git a/src/sage/categories/finite_fields.py b/src/sage/categories/finite_fields.py index a78f1a0c347..b62bed4ed28 100644 --- a/src/sage/categories/finite_fields.py +++ b/src/sage/categories/finite_fields.py @@ -75,7 +75,7 @@ def _call_(self, x): ... TypeError: unable to canonically associate a finite field to Rational Field """ - raise TypeError, "unable to canonically associate a finite field to %s"%x + raise TypeError("unable to canonically associate a finite field to %s"%x) # TODO: local dvr ring? #@lazy_attribute diff --git a/src/sage/categories/function_fields.py b/src/sage/categories/function_fields.py index 811479cd03e..efe9446a41d 100644 --- a/src/sage/categories/function_fields.py +++ b/src/sage/categories/function_fields.py @@ -65,7 +65,7 @@ def _call_(self, x): try: return x.function_field() except AttributeError: - raise TypeError, "unable to canonically associate a function field to %s"%x + raise TypeError("unable to canonically associate a function field to %s"%x) class ParentMethods: pass diff --git a/src/sage/categories/hecke_modules.py b/src/sage/categories/hecke_modules.py index 645aa111ab9..5fdd79649db 100644 --- a/src/sage/categories/hecke_modules.py +++ b/src/sage/categories/hecke_modules.py @@ -71,7 +71,7 @@ def __init__(self, R): """ from commutative_rings import CommutativeRings if R not in CommutativeRings(): - raise TypeError, "R (=%s) must be a commutative ring"%R + raise TypeError("R (=%s) must be a commutative ring"%R) Category_module.__init__(self, R, "Hecke modules") def super_categories(self): @@ -128,7 +128,7 @@ def _Hom_(self, Y, category): """ # TODO: double check that it's the correct HeckeModules category below: if category is not None and not category.is_subcategory(HeckeModules(self.base_ring())): - raise TypeError, "%s is not a subcategory of %s"%(category, HeckeModules(self.base_ring())) + raise TypeError("%s is not a subcategory of %s"%(category, HeckeModules(self.base_ring()))) from sage.modular.hecke.homspace import HeckeModuleHomspace return HeckeModuleHomspace(self, Y, category = category) diff --git a/src/sage/categories/homset.py b/src/sage/categories/homset.py index 564055bd14c..d2a2da89f89 100644 --- a/src/sage/categories/homset.py +++ b/src/sage/categories/homset.py @@ -294,7 +294,7 @@ def Hom(X, Y, category=None): H = Hom(X, Y, category) else: if not isinstance(category, Category): - raise TypeError, "Argument category (= %s) must be a category."%category + raise TypeError("Argument category (= %s) must be a category."%category) # See trac #14793: It can happen, that Hom(X,X) is called during # unpickling of an instance X of a Python class at a time when # X.__dict__ is empty. In some of these cases, X.category() would @@ -324,19 +324,19 @@ def Hom(X, Y, category=None): try: cat_X = X.category() except BaseException: - raise TypeError, "%s is not in %s"%(X, category) + raise TypeError("%s is not in %s"%(X, category)) if unpickle_Y: cat_Y = category else: try: cat_Y = Y.category() except BaseException: - raise TypeError, "%s is not in %s"%(Y, category) + raise TypeError("%s is not in %s"%(Y, category)) if not cat_X.is_subcategory(category): - raise TypeError, "%s is not in %s"%(X, category) + raise TypeError("%s is not in %s"%(X, category)) if not cat_Y.is_subcategory(category): - raise TypeError, "%s is not in %s"%(Y, category) + raise TypeError("%s is not in %s"%(Y, category)) # Construct H try: # _Hom_ hook from the parent @@ -500,7 +500,7 @@ def __init__(self, X, Y, category=None, base = None, check=True): self.__category = category if check: if not isinstance(category, Category): - raise TypeError, "category (=%s) must be a category"%category + raise TypeError("category (=%s) must be a category"%category) #if not X in category: # raise TypeError, "X (=%s) must be in category (=%s)"%(X, category) #if not Y in category: @@ -714,19 +714,19 @@ def __call__(self, x=None, y=None, check=True, **options): if x.domain() != self.domain(): mor = x.domain().coerce_map_from(self.domain()) if mor is None: - raise TypeError, "Incompatible domains: x (=%s) cannot be an element of %s"%(x,self) + raise TypeError("Incompatible domains: x (=%s) cannot be an element of %s"%(x,self)) x = x * mor if x.codomain() != self.codomain(): mor = self.codomain().coerce_map_from(x.codomain()) if mor is None: - raise TypeError, "Incompatible codomains: x (=%s) cannot be an element of %s"%(x,self) + raise TypeError("Incompatible codomains: x (=%s) cannot be an element of %s"%(x,self)) x = mor * x return x if isinstance(x, (types.FunctionType, types.MethodType, ConstantFunction)): return self.element_class_set_morphism(self, x) - raise TypeError, "Unable to coerce x (=%s) to a morphism in %s"%(x,self) + raise TypeError("Unable to coerce x (=%s) to a morphism in %s"%(x,self)) @lazy_attribute def element_class_set_morphism(self): @@ -850,7 +850,7 @@ def identity(self): if self.is_endomorphism_set(): return morphism.IdentityMorphism(self) else: - raise TypeError, "Identity map only defined for endomorphisms. Try natural_map() instead." + raise TypeError("Identity map only defined for endomorphisms. Try natural_map() instead.") def domain(self): """ diff --git a/src/sage/categories/infinite_enumerated_sets.py b/src/sage/categories/infinite_enumerated_sets.py index a7ef631339c..7efeab5ecd6 100644 --- a/src/sage/categories/infinite_enumerated_sets.py +++ b/src/sage/categories/infinite_enumerated_sets.py @@ -95,7 +95,7 @@ def random_element(self): TODO: should this be an optional abstract_method instead? """ - raise NotImplementedError, "infinite set" + raise NotImplementedError("infinite set") def list(self): """ @@ -109,7 +109,7 @@ def list(self): ... NotImplementedError: infinite list """ - raise NotImplementedError, "infinite list" + raise NotImplementedError("infinite list") _list_default = list # needed by the check system. def _test_enumerated_set_iter_cardinality(self, **options): diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py index 69668b34fb6..1d042c4b920 100644 --- a/src/sage/categories/modules_with_basis.py +++ b/src/sage/categories/modules_with_basis.py @@ -162,7 +162,7 @@ def _call_(self, x): if M.base_ring() != self.base_ring(): M = M.change_ring(self.base_ring()) except (TypeError, AttributeError) as msg: - raise TypeError, "%s\nunable to coerce x (=%s) into %s"%(msg,x,self) + raise TypeError("%s\nunable to coerce x (=%s) into %s"%(msg,x,self)) return M def is_abelian(self): @@ -487,7 +487,7 @@ def support_of_term(self): if len(self) == 1: return self.support()[0] else: - raise ValueError, "%s is not a single term"%(self) + raise ValueError("%s is not a single term"%(self)) def leading_support(self, cmp=None): r""" @@ -1699,7 +1699,7 @@ def __invert__(self): 1/2*B[2] - 1/2*B[3] """ if not self._invertible: - raise ValueError, "Non invertible morphism" + raise ValueError("Non invertible morphism") else: return self.section() diff --git a/src/sage/categories/number_fields.py b/src/sage/categories/number_fields.py index e83e43bffb5..457a32c1622 100644 --- a/src/sage/categories/number_fields.py +++ b/src/sage/categories/number_fields.py @@ -113,7 +113,7 @@ def _call_(self, x): try: return x.number_field() except AttributeError: - raise TypeError, "unable to canonically associate a number field to %s"%x + raise TypeError("unable to canonically associate a number field to %s"%x) class ParentMethods: diff --git a/src/sage/categories/polyhedra.py b/src/sage/categories/polyhedra.py index 5c86791bd73..227ea51e17f 100644 --- a/src/sage/categories/polyhedra.py +++ b/src/sage/categories/polyhedra.py @@ -56,7 +56,7 @@ def __init__(self, R): """ from sage.rings.all import ZZ, QQ, RDF if R not in [ZZ, QQ, RDF]: - raise TypeError, 'base ring R (='+str(R)+') must be ZZ, QQ, or RDF.' + raise TypeError('base ring R (='+str(R)+') must be ZZ, QQ, or RDF.') Category_over_base_ring.__init__(self, R, 'Polyhedra') @cached_method diff --git a/src/sage/categories/pushout.py b/src/sage/categories/pushout.py index 57f6c89b730..e3a292f256f 100644 --- a/src/sage/categories/pushout.py +++ b/src/sage/categories/pushout.py @@ -117,7 +117,7 @@ def __mul__(self, other): """ if not isinstance(self, ConstructionFunctor) and not isinstance(other, ConstructionFunctor): - raise CoercionException, "Non-constructive product" + raise CoercionException("Non-constructive product") if isinstance(other,IdentityConstructionFunctor): return self if isinstance(self,IdentityConstructionFunctor): @@ -824,9 +824,9 @@ def __mul__(self, other): return self if isinstance(other, MultiPolynomialFunctor): if self.term_order != other.term_order: - raise CoercionException, "Incompatible term orders (%s,%s)." % (self.term_order, other.term_order) + raise CoercionException("Incompatible term orders (%s,%s)." % (self.term_order, other.term_order)) if set(self.vars).intersection(other.vars): - raise CoercionException, "Overlapping variables (%s,%s)" % (self.vars, other.vars) + raise CoercionException("Overlapping variables (%s,%s)" % (self.vars, other.vars)) return MultiPolynomialFunctor(other.vars + self.vars, self.term_order) elif isinstance(other, CompositeConstructionFunctor) \ and isinstance(other.all[-1], MultiPolynomialFunctor): @@ -997,7 +997,7 @@ def __init__(self, gens, order, implementation): """ if len(gens)<1: - raise ValueError, "Infinite Polynomial Rings have at least one generator" + raise ValueError("Infinite Polynomial Rings have at least one generator") ConstructionFunctor.__init__(self, Rings(), Rings()) self._gens = tuple(gens) self._order = order @@ -1018,7 +1018,7 @@ def _apply_functor_to_morphism(self, f): NotImplementedError: Morphisms for inifinite polynomial rings are not implemented yet. """ - raise NotImplementedError, "Morphisms for inifinite polynomial rings are not implemented yet." + raise NotImplementedError("Morphisms for inifinite polynomial rings are not implemented yet.") def _apply_functor(self, R): """ @@ -1096,7 +1096,7 @@ def __mul__(self, other): # if there is overlap of generators, it must only be at the ends, so that # the resulting order after the merging is unique if other._gens[-len(INT):] != self._gens[:len(INT)]: - raise CoercionException, "Overlapping variables (%s,%s) are incompatible" % (self._gens, other._gens) + raise CoercionException("Overlapping variables (%s,%s) are incompatible" % (self._gens, other._gens)) OUTGENS = list(other._gens) + list(self._gens[len(INT):]) else: OUTGENS = list(other._gens) + list(self._gens) @@ -1157,10 +1157,10 @@ def __mul__(self, other): BadOverlap = True if BadOverlap: # the overlapping variables appear in the wrong order - raise CoercionException, "Overlapping variables (%s,%s) are incompatible" % (self._gens, OverlappingVars) + raise CoercionException("Overlapping variables (%s,%s) are incompatible" % (self._gens, OverlappingVars)) if len(OverlappingVars)>1: # multivariate, hence, the term order matters if other.term_order.name()!=self._order: - raise CoercionException, "Incompatible term orders %s, %s" % (self._order, other.term_order.name()) + raise CoercionException("Incompatible term orders %s, %s" % (self._order, other.term_order.name())) # ok, the overlap is fine, we will return something. if RemainingVars: # we can only partially merge other into self if len(RemainingVars)>1: @@ -1428,7 +1428,7 @@ def __init__(self, var, multi_variate=False): """ Functor.__init__(self, Rings(), Rings()) if not isinstance(var, (basestring,tuple,list)): - raise TypeError, "variable name or list of variable names expected" + raise TypeError("variable name or list of variable names expected") self.var = var self.multi_variate = multi_variate or not isinstance(var, basestring) @@ -1603,7 +1603,7 @@ def _apply_functor_to_morphism(self, f): NotImplementedError: Can not create induced morphisms of free modules yet """ ## TODO: Implement this! - raise NotImplementedError, "Can not create induced morphisms of free modules yet" + raise NotImplementedError("Can not create induced morphisms of free modules yet") def __cmp__(self, other): """ @@ -1779,7 +1779,7 @@ def _apply_functor_to_morphism(self, f): ... NotImplementedError: Can not create morphisms of free sub-modules yet """ - raise NotImplementedError, "Can not create morphisms of free sub-modules yet" + raise NotImplementedError("Can not create morphisms of free sub-modules yet") def __cmp__(self, other): """ @@ -2111,14 +2111,14 @@ def _apply_functor(self, R): return R.completion(self.p, self.prec, extras) except (NotImplementedError,AttributeError): if R.construction() is None: - raise NotImplementedError, "Completion is not implemented for %s"%R.__class__ + raise NotImplementedError("Completion is not implemented for %s"%R.__class__) F, BR = R.construction() M = self.merge(F) or F.merge(self) if M is not None: return M(BR) if self.commutes(F) or F.commutes(self): return F(self(BR)) - raise NotImplementedError, "Don't know how to apply %s to %s"%(repr(self),repr(R)) + raise NotImplementedError("Don't know how to apply %s to %s"%(repr(self),repr(R))) def __cmp__(self, other): """ @@ -2403,7 +2403,7 @@ def _apply_functor(self, R): try: Q = R.quo(I,names=self.names) except IndexError: # That may happen! - raise CoercionException, "Can not apply this quotient functor to %s"%R + raise CoercionException("Can not apply this quotient functor to %s"%R) if self.as_field:# and hasattr(Q, 'field'): try: Q = Q.field() @@ -2473,7 +2473,7 @@ def merge(self, other): # quotient by gcd would result in the trivial ring/group/... # Rather than create the zero ring, we claim they can't be merged # TODO: Perhaps this should be detected at a higher level... - raise TypeError, "Trivial quotient intersection." + raise TypeError("Trivial quotient intersection.") # GF(p) has a coercion from Integers(p). Hence, merging should # yield a field if either self or other yields a field. return QuotientFunctor(gcd, names=self.names, as_field=self.as_field or other.as_field) @@ -2597,9 +2597,9 @@ def __init__(self, polys, names, embeddings, cyclotomic=None, **kwds): """ Functor.__init__(self, Rings(), Rings()) if not (isinstance(polys,(list,tuple)) and isinstance(names,(list,tuple)) and isinstance(embeddings,(list,tuple))): - raise ValueError, "Arguments must be lists or tuples" + raise ValueError("Arguments must be lists or tuples") if not (len(names)==len(polys)==len(embeddings)): - raise ValueError, "The three arguments must be of the same length" + raise ValueError("The three arguments must be of the same length") self.polys = list(polys) self.names = list(names) self.embeddings = list(embeddings) @@ -2800,7 +2800,7 @@ def __mul__(self, other): return self if isinstance(other, AlgebraicExtensionFunctor): if set(self.names).intersection(other.names): - raise CoercionException, "Overlapping names (%s,%s)" % (self.names, other.names) + raise CoercionException("Overlapping names (%s,%s)" % (self.names, other.names)) return AlgebraicExtensionFunctor(self.polys + other.polys, self.names + other.names, self.embeddings + other.embeddings, **self.kwds) elif isinstance(other, CompositeConstructionFunctor) \ @@ -3024,7 +3024,7 @@ def __init__(self, box): """ ConstructionFunctor.__init__(self,Objects(),Objects()) if not callable(box): - raise TypeError, "input must be callable" + raise TypeError("input must be callable") self.box = box def _apply_functor(self, R): @@ -3194,7 +3194,7 @@ def pushout(R, S): Z = Rs.pop() else: - raise CoercionException, "No common base" + raise CoercionException("No common base") # Rc is a list of functors from Z to R and Sc is a list of functors from Z to S Rc = [c[0] for c in R_tower[1:len(Rs)+1]] @@ -3231,7 +3231,7 @@ def pushout(R, S): if c: all = c * all else: - raise CoercionException, "Incompatible Base Extension %r, %r (on %r, %r)" % (R, S, cR, cS) + raise CoercionException("Incompatible Base Extension %r, %r (on %r, %r)" % (R, S, cR, cS)) else: # Now we look ahead to see if either top functor is # applied later on in the other tower. @@ -3239,7 +3239,7 @@ def pushout(R, S): # postpone that operation, but if both then we abort. if Rc[-1] in Sc: if Sc[-1] in Rc: - raise CoercionException, ("Ambiguous Base Extension", R, S) + raise CoercionException("Ambiguous Base Extension", R, S) else: all = Sc.pop() * all elif Sc[-1] in Rc: @@ -3256,7 +3256,7 @@ def pushout(R, S): all = c * all else: # Otherwise, we cannot proceed. - raise CoercionException, ("Ambiguous Base Extension", R, S) + raise CoercionException("Ambiguous Base Extension", R, S) return all(Z) @@ -3397,7 +3397,7 @@ def pushout_lattice(R, S): print i, j, R except KeyError: break - raise CoercionException, "%s does not support %s" % (lattice[i,j], 'F') + raise CoercionException("%s does not support %s" % (lattice[i,j], 'F')) # If we are successful, we should have something that looks like this. # @@ -3514,4 +3514,4 @@ def type_to_parent(P): elif P is complex: return sage.rings.all.CDF else: - raise TypeError, "Not a scalar type." + raise TypeError("Not a scalar type.") diff --git a/src/sage/categories/quotient_fields.py b/src/sage/categories/quotient_fields.py index c848ec8c670..68145406ebb 100644 --- a/src/sage/categories/quotient_fields.py +++ b/src/sage/categories/quotient_fields.py @@ -113,7 +113,7 @@ def gcd(self,other): try: other = self.parent()(other) except (TypeError, ValueError): - raise ArithmeticError, "The second argument can not be interpreted in the parent of the first argument. Can't compute the gcd" + raise ArithmeticError("The second argument can not be interpreted in the parent of the first argument. Can't compute the gcd") try: selfN = self.numerator() selfD = self.denominator() @@ -192,7 +192,7 @@ def lcm(self,other): try: other = self.parent()(other) except (TypeError, ValueError): - raise ArithmeticError, "The second argument can not be interpreted in the parent of the first argument. Can't compute the lcm" + raise ArithmeticError("The second argument can not be interpreted in the parent of the first argument. Can't compute the lcm") try: selfN = self.numerator() selfD = self.denominator() diff --git a/src/sage/categories/ring_ideals.py b/src/sage/categories/ring_ideals.py index 1a1d60498d5..88ad98e2f00 100644 --- a/src/sage/categories/ring_ideals.py +++ b/src/sage/categories/ring_ideals.py @@ -55,7 +55,7 @@ def __init__(self, R): sage: TestSuite(RingIdeals(ZZ)).run() """ if not R in _Rings: - raise TypeError, "R (=%s) must be a ring"%R + raise TypeError("R (=%s) must be a ring"%R) Category_ideal.__init__(self, R) def super_categories(self): diff --git a/src/sage/categories/rings.py b/src/sage/categories/rings.py index 340b88a08c1..b66c06d7e12 100644 --- a/src/sage/categories/rings.py +++ b/src/sage/categories/rings.py @@ -152,9 +152,9 @@ def _Hom_(self, Y, category): """ if category is not None and not category.is_subcategory(Rings()): - raise TypeError, "%s is not a subcategory of Rings()"%category + raise TypeError("%s is not a subcategory of Rings()"%category) if Y not in Rings(): - raise TypeError, "%s is not a ring"%Y + raise TypeError("%s is not a ring"%Y) from sage.rings.homset import RingHomset return RingHomset(self, Y, category = category) @@ -244,7 +244,7 @@ def _mul_(self, x, switch_sides=False): elif side=='right': return self.ideal(x,side='twosided') # duck typing failed - raise TypeError, "Don't know how to transform %s into an ideal of %s"%(x,self) + raise TypeError("Don't know how to transform %s into an ideal of %s"%(x,self)) @cached_method def ideal_monoid(self): @@ -407,7 +407,7 @@ def ideal(self, *args, **kwds): elif hasattr(first,'parent'): gens = [first] else: - raise ArithmeticError, "There is no coercion from %s to %s"%(first,self) + raise ArithmeticError("There is no coercion from %s to %s"%(first,self)) except TypeError: # first may be a ring element pass break @@ -637,7 +637,7 @@ def __div__(self, I): ... TypeError: Use self.quo(I) or self.quotient(I) to construct the quotient ring. """ - raise TypeError, "Use self.quo(I) or self.quotient(I) to construct the quotient ring." + raise TypeError("Use self.quo(I) or self.quotient(I) to construct the quotient ring.") def __getitem__(self, arg): """ diff --git a/src/sage/categories/schemes.py b/src/sage/categories/schemes.py index f72c07bdf61..c7103ec1063 100644 --- a/src/sage/categories/schemes.py +++ b/src/sage/categories/schemes.py @@ -130,7 +130,7 @@ def _call_(self, x): A = Spec(x.codomain()) return A.hom(x) else: - raise TypeError, "No way to create an object or morphism in %s from %s"%(self, x) + raise TypeError("No way to create an object or morphism in %s from %s"%(self, x)) class HomCategory(HomCategory): diff --git a/src/sage/categories/semigroups.py b/src/sage/categories/semigroups.py index ceff3995e9a..1d2ddae8dd2 100644 --- a/src/sage/categories/semigroups.py +++ b/src/sage/categories/semigroups.py @@ -268,7 +268,7 @@ def cayley_graph(self, side="right", simple=False, elements = None, generators = from sage.graphs.digraph import DiGraph from groups import Groups if not side in ["left", "right", "twosided"]: - raise ValueError, "option 'side' must be 'left', 'right' or 'twosided'" + raise ValueError("option 'side' must be 'left', 'right' or 'twosided'") if elements is None: assert self.is_finite(), "elements should be specified for infinite semigroups" elements = list(self) diff --git a/src/sage/categories/sets_cat.py b/src/sage/categories/sets_cat.py index 989e4026a4c..e128d92148f 100644 --- a/src/sage/categories/sets_cat.py +++ b/src/sage/categories/sets_cat.py @@ -274,7 +274,7 @@ def example(self, choice = None): from sage.categories.examples.sets_cat import PrimeNumbers_Wrapper return PrimeNumbers_Wrapper() else: - raise ValueError, "Unkown choice" + raise ValueError("Unkown choice") class ParentMethods: # # currently overriden by the default implementation in sage.structure.Parent diff --git a/src/sage/categories/vector_spaces.py b/src/sage/categories/vector_spaces.py index 24dde75412b..73c13cdc7ca 100644 --- a/src/sage/categories/vector_spaces.py +++ b/src/sage/categories/vector_spaces.py @@ -95,7 +95,7 @@ def __call__(self, x): if V.base_field() != self.base_field(): V = V.change_ring(self.base_field()) except (TypeError, AttributeError) as msg: - raise TypeError, "%s\nunable to coerce x (=%s) into %s"%(msg,x,self) + raise TypeError("%s\nunable to coerce x (=%s) into %s"%(msg,x,self)) return V def base_field(self): diff --git a/src/sage/categories/weyl_groups.py b/src/sage/categories/weyl_groups.py index 3da27bef83b..44e54782519 100644 --- a/src/sage/categories/weyl_groups.py +++ b/src/sage/categories/weyl_groups.py @@ -133,7 +133,7 @@ def quantum_bruhat_graph(self, index_set = ()): ValueError: The Cartan type ['A', 3, 1] is not finite """ if not self.cartan_type().is_finite(): - raise ValueError, "The Cartan type %s is not finite"%(self.cartan_type()) + raise ValueError("The Cartan type %s is not finite"%(self.cartan_type())) from sage.graphs.digraph import DiGraph WP = [x for x in self if x==x.coset_representative(index_set)] return DiGraph([[x,i[0],i[1]] for x in WP for i in x.quantum_bruhat_successors(index_set, roots = True)], @@ -391,13 +391,13 @@ def reflection_to_root(self): i = self.first_descent() if i is None: - raise ValueError, "%s is not a reflection"%(self) + raise ValueError("%s is not a reflection"%(self)) if self == self.parent().simple_reflection(i): from sage.combinat.root_system.root_system import RootSystem return RootSystem(self.parent().cartan_type()).root_lattice().simple_root(i) #return self.parent().domain().simple_root(i) if not self.has_descent(i, side='left'): - raise ValueError, "%s is not a reflection"%(self) + raise ValueError("%s is not a reflection"%(self)) return ((self.apply_conjugation_by_simple_reflection(i)).reflection_to_root()).simple_reflection(i) @cached_in_parent_method @@ -421,13 +421,13 @@ def reflection_to_coroot(self): i = self.first_descent() if i is None: - raise ValueError, "%s is not a reflection"%(self) + raise ValueError("%s is not a reflection"%(self)) if self == self.parent().simple_reflection(i): from sage.combinat.root_system.root_system import RootSystem return RootSystem(self.parent().cartan_type()).root_lattice().simple_coroot(i) #return self.parent().domain().simple_coroot(i) if not self.has_descent(i, side='left'): - raise ValueError, "%s is not a reflection"%(self) + raise ValueError("%s is not a reflection"%(self)) return ((self.apply_conjugation_by_simple_reflection(i)).reflection_to_coroot()).simple_reflection(i) def inversions(self, side = 'right', inversion_type = 'reflections'): @@ -477,7 +477,7 @@ def inversions(self, side = 'right', inversion_type = 'reflections'): return [r.reflection_to_root() for r in reflections] if inversion_type == 'coroots': return [r.reflection_to_coroot() for r in reflections] - raise ValueError, "inversion_type %s is invalid"%(inversion_type) + raise ValueError("inversion_type %s is invalid"%(inversion_type)) def bruhat_lower_covers_coroots(self): r""" @@ -564,13 +564,13 @@ def quantum_bruhat_successors(self, index_set = None, roots = False, quantum_onl """ W = self.parent() if not W.cartan_type().is_finite(): - raise ValueError, "The Cartan type %s is not finite"%(W.cartan_type()) + raise ValueError("The Cartan type %s is not finite"%(W.cartan_type())) if index_set is None: index_set = [] else: index_set = [x for x in index_set] if self != self.coset_representative(index_set): - raise ValueError, "%s is not of minimum length in its coset of the parabolic subgroup generated by the reflections %s"%(self,index_set) + raise ValueError("%s is not of minimum length in its coset of the parabolic subgroup generated by the reflections %s"%(self,index_set)) lattice = W.cartan_type().root_system().root_lattice() non_parab_roots = lattice.positive_roots_nonparabolic(tuple(index_set)) two_rho_minus_two_rho_P = lattice.positive_roots_nonparabolic_sum(tuple(index_set)) diff --git a/src/sage/coding/code_constructions.py b/src/sage/coding/code_constructions.py index 892c7344500..e5875606f18 100644 --- a/src/sage/coding/code_constructions.py +++ b/src/sage/coding/code_constructions.py @@ -222,11 +222,11 @@ def cyclotomic_cosets(q, n, t = None): """ from sage.misc.misc import srange if t is not None and not isinstance(t, Integer): - raise TypeError, "Optional input %s must None or an integer."%t + raise TypeError("Optional input %s must None or an integer."%t) if q<2 or n<2: - raise TypeError, "Inputs %s and %s must be > 1."%(q,n) + raise TypeError("Inputs %s and %s must be > 1."%(q,n)) if GCD(q,n) != 1: - raise TypeError, "Inputs %s and %s must be relative prime."%(q,n) + raise TypeError("Inputs %s and %s must be relative prime."%(q,n)) if t is not None and isinstance(t, Integer): S = Set([t*q**i%n for i in srange(n)]) L = list(S) @@ -303,9 +303,9 @@ def is_a_splitting(S1,S2,n): This is a special case of Theorem 6.4.3 in [HP]_. """ if Set(S1).union(Set(S2)) != Set(range(1,n)): - raise TypeError, "Lists must partition [1,2,...,n-1]." + raise TypeError("Lists must partition [1,2,...,n-1].") if n<3: - raise TypeError, "Input %s must be > 2."%n + raise TypeError("Input %s must be > 2."%n) for b in range(2,n): SS1 = Set([b*x%n for x in S1]) SS2 = Set([b*x%n for x in S2]) @@ -489,7 +489,7 @@ def walsh_matrix(m0): if m > 1: row2 = [x.list() for x in walsh_matrix(m-1).augment(walsh_matrix(m-1)).rows()] return matrix(GF(2), m, 2**m, [[0]*2**(m-1) + [1]*2**(m-1)] + row2) - raise ValueError, "%s must be an integer > 0."%m0 + raise ValueError("%s must be an integer > 0."%m0) ##################### main constructions ##################### @@ -563,7 +563,7 @@ def BCHCode(n,delta,F,b=0): g = P(LCM(L1)) #print cosets, "\n", g, "\n", (x**n-1).factor(), "\n", L1, "\n", g.divides(x**n-1) if not(g.divides(x**n-1)): - raise ValueError, "BCH codes does not exist with the given input." + raise ValueError("BCH codes does not exist with the given input.") return CyclicCodeFromGeneratingPolynomial(n,g) @@ -677,9 +677,9 @@ def CyclicCodeFromGeneratingPolynomial(n,g,ignore=True): F = g.base_ring() p = F.characteristic() if not(ignore) and p.divides(n): - raise ValueError, 'The characteristic %s must not divide %s'%(p,n) + raise ValueError('The characteristic %s must not divide %s'%(p,n)) if not(ignore) and not(g.divides(x**n-1)): - raise ValueError, '%s must divide x^%s - 1'%(g,n) + raise ValueError('%s must divide x^%s - 1'%(g,n)) gn = GCD([g,x**n-1]) d = gn.degree() coeffs = Sequence(gn.list()) @@ -720,9 +720,9 @@ def CyclicCodeFromCheckPolynomial(n,h,ignore=True): F = h.base_ring() p = F.characteristic() if not(ignore) and p.divides(n): - raise ValueError, 'The characteristic %s must not divide %s'%(p,n) + raise ValueError('The characteristic %s must not divide %s'%(p,n)) if not(h.divides(x**n-1)): - raise ValueError, '%s must divide x^%s - 1'%(h,n) + raise ValueError('%s must divide x^%s - 1'%(h,n)) g = P((x**n-1)/h) return CyclicCodeFromGeneratingPolynomial(n,g) @@ -753,7 +753,7 @@ def DuadicCodeEvenPair(F,S1,S2): """ n = max(S1+S2)+1 if not(is_a_splitting(S1,S2,n)): - raise TypeError, "%s, %s must be a splitting of %s."%(S1,S2,n) + raise TypeError("%s, %s must be a splitting of %s."%(S1,S2,n)) q = F.order() k = Mod(q,n).multiplicative_order() FF = GF(q**k,"z") @@ -799,7 +799,7 @@ def DuadicCodeOddPair(F,S1,S2): """ n = max(S1+S2)+1 if not(is_a_splitting(S1,S2,n)): - raise TypeError, "%s, %s must be a splitting of %s."%(S1,S2,n) + raise TypeError("%s, %s must be a splitting of %s."%(S1,S2,n)) q = F.order() k = Mod(q,n).multiplicative_order() FF = GF(q**k,"z") @@ -1113,9 +1113,9 @@ def QuadraticResidueCodeEvenPair(n,F): Q = quadratic_residues(n); Q.remove(0) # non-zero quad residues N = range(1,n); tmp = [N.remove(x) for x in Q] # non-zero quad non-residues if (n.is_prime() and n>2 and not(q in Q)): - raise ValueError, "No quadratic residue code exists for these parameters." + raise ValueError("No quadratic residue code exists for these parameters.") if not(is_a_splitting(Q,N,n)): - raise TypeError, "No quadratic residue code exists for these parameters." + raise TypeError("No quadratic residue code exists for these parameters.") return DuadicCodeEvenPair(F,Q,N) @@ -1165,9 +1165,9 @@ def QuadraticResidueCodeOddPair(n,F): Q = quadratic_residues(n); Q.remove(0) # non-zero quad residues N = range(1,n); tmp = [N.remove(x) for x in Q] # non-zero quad non-residues if (n.is_prime() and n>2 and not(q in Q)): - raise ValueError, "No quadratic residue code exists for these parameters." + raise ValueError("No quadratic residue code exists for these parameters.") if not(is_a_splitting(Q,N,n)): - raise TypeError, "No quadratic residue code exists for these parameters." + raise TypeError("No quadratic residue code exists for these parameters.") return DuadicCodeOddPair(F,Q,N) @@ -1268,9 +1268,9 @@ def ReedSolomonCode(n,k,F,pts = None): q = F.order() power = lambda x,n,F: (x==0 and n==0) and F(1) or F(x**n) # since 0^0 is undefined if n>q or k>n or k>q: - raise ValueError, "RS codes does not exist with the given input." + raise ValueError("RS codes does not exist with the given input.") if not(pts == None) and not(len(pts)==n): - raise ValueError, "You must provide exactly %s distinct points of %s"%(n,F) + raise ValueError("You must provide exactly %s distinct points of %s"%(n,F)) if (pts == None): pts = [] i = 0 diff --git a/src/sage/coding/linear_code.py b/src/sage/coding/linear_code.py index ee0aa7a6f3a..3c9065698ea 100644 --- a/src/sage/coding/linear_code.py +++ b/src/sage/coding/linear_code.py @@ -513,7 +513,7 @@ def best_known_linear_code_www(n, k, F, verbose=False): """ q = F.order() if not q in [2, 3, 4, 5, 7, 8, 9]: - raise ValueError, "q (=%s) must be in [2,3,4,5,7,8,9]"%q + raise ValueError("q (=%s) must be in [2,3,4,5,7,8,9]"%q) n = int(n) k = int(k) @@ -531,7 +531,7 @@ def best_known_linear_code_www(n, k, F, verbose=False): i = s.find("
")
     j = s.find("
") if i == -1 or j == -1: - raise IOError, "Error parsing data (missing pre tags)." + raise IOError("Error parsing data (missing pre tags).") text = s[i+5:j].strip() return text @@ -900,7 +900,7 @@ def automorphism_group_binary_code(self): C = self F = C.base_ring() if F!=GF(2): - raise NotImplementedError, "Only implemented for binary codes." + raise NotImplementedError("Only implemented for binary codes.") return self.permutation_automorphism_group() def __iter__(self): @@ -1490,7 +1490,7 @@ def decode(self, right, algorithm="syndrome"): result = [gfq_gap_to_sage(v, self.base_ring()) for v in result] return self.ambient_space()(result) else: - raise NotImplementedError, "Only 'syndrome','nearest neighbor','guava' are implemented." + raise NotImplementedError("Only 'syndrome','nearest neighbor','guava' are implemented.") def divisor(self): r""" @@ -1685,7 +1685,7 @@ def galois_closure(self, F0): q0 = F0.order() a = log(q,q0) # test if F/F0 is a field extension if not isinstance(a, Integer): - raise ValueError,"Base field must be an extension of given field %s"%F0 + raise ValueError("Base field must be an extension of given field %s"%F0) n = len(G.columns()) k = len(G.rows()) G0 = [[x**q0 for x in g.list()] for g in G.rows()] diff --git a/src/sage/combinat/affine_permutation.py b/src/sage/combinat/affine_permutation.py index 72d4b091664..6817d47e15b 100644 --- a/src/sage/combinat/affine_permutation.py +++ b/src/sage/combinat/affine_permutation.py @@ -70,7 +70,7 @@ def __init__(self, parent, lst, check=True): elif parent.cartan_type()[0]=='G': self.N=6 else: - raise NotImplementedError, 'Unsupported Cartan Type.' + raise NotImplementedError('Unsupported Cartan Type.') ClonableArray.__init__(self, parent, lst, check) def _repr_(self): diff --git a/src/sage/combinat/binary_recurrence_sequences.py b/src/sage/combinat/binary_recurrence_sequences.py index 7c70e4b8cfa..df50cae1b28 100644 --- a/src/sage/combinat/binary_recurrence_sequences.py +++ b/src/sage/combinat/binary_recurrence_sequences.py @@ -606,7 +606,7 @@ def pthpowers(self, p, Bound): return [0] return [] else : - raise ValueError, "The degenerate binary recurrence sequence is geometric or quasigeometric and has many pth powers." + raise ValueError("The degenerate binary recurrence sequence is geometric or quasigeometric and has many pth powers.") #If the sequence is degenerate without being geometric or quasigeometric, there #may be many ``p`` th powers or no ``p`` th powers. @@ -633,7 +633,7 @@ def pthpowers(self, p, Bound): #This linear equation represents a pth power iff A is a pth power mod B. if _is_p_power_mod(A, p, B): - raise ValueError, "The degenerate binary recurrence sequence has many pth powers." + raise ValueError("The degenerate binary recurrence sequence has many pth powers.") return [] #We find ``p`` th powers using an elementary sieve. Term `u_n` is a ``p`` th diff --git a/src/sage/combinat/binary_tree.py b/src/sage/combinat/binary_tree.py index 1bc05e0a0f5..c14d7eeeb95 100644 --- a/src/sage/combinat/binary_tree.py +++ b/src/sage/combinat/binary_tree.py @@ -768,7 +768,7 @@ def to_dyck_word(self, usemap="1L0R"): """ from sage.combinat.dyck_word import DyckWord if usemap not in ["1L0R", "1R0L", "L1R0", "R1L0"]: - raise ValueError, "%s is not a correct map"%(usemap) + raise ValueError("%s is not a correct map"%(usemap)) return DyckWord(self._to_dyck_word_rec(usemap)) def _to_ordered_tree(self, bijection="left", root=None): diff --git a/src/sage/combinat/choose_nk.py b/src/sage/combinat/choose_nk.py index 8a4b80e8ca4..736eb0dca9f 100644 --- a/src/sage/combinat/choose_nk.py +++ b/src/sage/combinat/choose_nk.py @@ -169,7 +169,7 @@ def unrank(self, r): True """ if r < 0 or r >= self.cardinality(): - raise ValueError, "rank must be between 0 and %s (inclusive)"%(self.cardinality()-1) + raise ValueError("rank must be between 0 and %s (inclusive)"%(self.cardinality()-1)) return from_rank(r, self._n, self._k) def rank(self, x): @@ -217,7 +217,7 @@ def rank(comb, n): k = len(comb) if k > n: - raise ValueError, "len(comb) must be <= n" + raise ValueError("len(comb) must be <= n") #Generate the combinadic from the #combination @@ -285,9 +285,9 @@ def from_rank(r, n, k): [0, 1, 2] """ if k < 0: - raise ValueError, "k must be > 0" + raise ValueError("k must be > 0") if k > n: - raise ValueError, "k must be <= n" + raise ValueError("k must be <= n") a = n b = k diff --git a/src/sage/combinat/cluster_algebra_quiver/quiver_mutation_type.py b/src/sage/combinat/cluster_algebra_quiver/quiver_mutation_type.py index 4395795e9c8..f4a978da18d 100644 --- a/src/sage/combinat/cluster_algebra_quiver/quiver_mutation_type.py +++ b/src/sage/combinat/cluster_algebra_quiver/quiver_mutation_type.py @@ -1534,7 +1534,7 @@ def __init__(self, letter, rank, twist=None): if self._graph.is_bipartite(): self._digraph = _bipartite_graph_to_digraph( self._graph ) else: - raise ValueError, 'The QuiverMutationType does not have a Coxeter diagram.' + raise ValueError('The QuiverMutationType does not have a Coxeter diagram.') # in the other cases, the graph is constructed from the digraph if not self._graph: @@ -2093,7 +2093,7 @@ def _save_data_dig6(n, types='ClassicalExceptional', verbose=False): data = {} possible_types = ['Classical','ClassicalExceptional','Exceptional'] if types not in possible_types: - raise ValueError, 'The third input must be either ClassicalExceptional (default), Classical, or Exceptional.' + raise ValueError('The third input must be either ClassicalExceptional (default), Classical, or Exceptional.') if types in possible_types[:2]: data.update(_construct_classical_mutation_classes(n)) @@ -2182,7 +2182,7 @@ def _bipartite_graph_to_digraph( g ): Digraph on 2 vertices """ if not g.is_bipartite(): - raise ValueError, 'The input graph is not bipartite.' + raise ValueError('The input graph is not bipartite.') order = g.bipartite_sets() dg = DiGraph() @@ -2240,7 +2240,7 @@ def _mutation_type_error( data ): return_str += '\n Elliptic type ? has the form [ \'?\', k, [i, j] ] (1 <= i,j <= 3) for rank k+2' return_str += '\n For correct syntax in other types, please consult the documentation.' - raise ValueError, return_str + raise ValueError(return_str) def _edge_list_to_matrix( edges, n, m ): """ diff --git a/src/sage/combinat/combinat.py b/src/sage/combinat/combinat.py index c2a1cd8e235..6fe87c66ddc 100644 --- a/src/sage/combinat/combinat.py +++ b/src/sage/combinat/combinat.py @@ -449,7 +449,7 @@ def euler_number(n): """ n = ZZ(n) if n < 0: - raise ValueError, "n (=%s) must be a nonnegative integer"%n + raise ValueError("n (=%s) must be a nonnegative integer"%n) return ZZ(maxima.eval("euler(%s)"%n)) def fibonacci(n, algorithm="pari"): @@ -506,7 +506,7 @@ def fibonacci(n, algorithm="pari"): elif algorithm == 'gap': return ZZ(gap.eval("Fibonacci(%s)"%n)) else: - raise ValueError, "no algorithm %s"%algorithm + raise ValueError("no algorithm %s"%algorithm) def lucas_number1(n,P,Q): """ @@ -1188,7 +1188,7 @@ def __len__(self): ... AttributeError: __len__ has been removed; use .cardinality() instead """ - raise AttributeError, "__len__ has been removed; use .cardinality() instead" + raise AttributeError("__len__ has been removed; use .cardinality() instead") def is_finite(self): """ @@ -1334,7 +1334,7 @@ def __call__(self, x): if x in self: return self._element_constructor_(x) else: - raise ValueError, "%s not in %s"%(x, self) + raise ValueError("%s not in %s"%(x, self)) Element = CombinatorialObject # mostly for backward compatibility @lazy_attribute @@ -1527,7 +1527,7 @@ def __iter__(self): elif self.list != self.__list_from_iterator: return self.__iterator_from_list() else: - raise NotImplementedError, "iterator called but not implemented" + raise NotImplementedError("iterator called but not implemented") def __unrank_from_iterator(self, r): """ @@ -1545,7 +1545,7 @@ def __unrank_from_iterator(self, r): if counter == r: return u counter += 1 - raise ValueError, "the value must be between %s and %s inclusive"%(0,counter-1) + raise ValueError("the value must be between %s and %s inclusive"%(0,counter-1)) #Set the default implementation of unrank unrank = __unrank_from_iterator @@ -1582,7 +1582,7 @@ def random(self): ... NotImplementedError: Deprecated: use random_element() instead """ - raise NotImplementedError, "Deprecated: use random_element() instead" + raise NotImplementedError("Deprecated: use random_element() instead") def __rank_from_iterator(self, obj): """ @@ -1705,7 +1705,7 @@ def union(self, right_cc, name=None): [[1, 2], [2, 1], [1]] """ if not isinstance(right_cc, CombinatorialClass): - raise TypeError, "right_cc must be a CombinatorialClass" + raise TypeError("right_cc must be a CombinatorialClass") return UnionCombinatorialClass(self, right_cc, name=name) def map(self, f, name=None): @@ -2126,7 +2126,7 @@ def list(self): ... NotImplementedError: infinite list """ - raise NotImplementedError, "infinite list" + raise NotImplementedError("infinite list") def __iter__(self): """ @@ -2769,7 +2769,7 @@ def bernoulli_polynomial(x, n): if n < 0: raise TypeError except TypeError: - raise ValueError, "The second argument must be a non-negative integer" + raise ValueError("The second argument must be a non-negative integer") if n == 0: return ZZ(1) diff --git a/src/sage/combinat/combinatorial_algebra.py b/src/sage/combinat/combinatorial_algebra.py index e0c0758691e..1ee001e78d0 100644 --- a/src/sage/combinat/combinatorial_algebra.py +++ b/src/sage/combinat/combinatorial_algebra.py @@ -121,7 +121,7 @@ def __invert__(self): if len(mcs) == 1 and one in mcs: return self.parent()( ~mcs[ one ] ) else: - raise ValueError, "cannot invert self (= %s)"%self + raise ValueError("cannot invert self (= %s)"%self) @@ -173,9 +173,9 @@ def __init__(self, R, cc = None, element_class = None, category = None): required = ['_one',] for r in required: if not hasattr(self, r): - raise ValueError, "%s is required"%r + raise ValueError("%s is required"%r) if not hasattr(self, '_multiply') and not hasattr(self, '_multiply_basis'): - raise ValueError, "either _multiply or _multiply_basis is required" + raise ValueError("either _multiply or _multiply_basis is required") #Create a class for the elements of this combinatorial algebra #We need to do this so to distinguish between element of different @@ -233,7 +233,7 @@ def __call__(self, x): else: return eclass(self, {self._one:R(x)}) - raise TypeError, "do not know how to make x (= %s) an element of self (=%s)"%(x,self) + raise TypeError("do not know how to make x (= %s) an element of self (=%s)"%(x,self)) def _an_element_impl(self): """ diff --git a/src/sage/combinat/combinatorial_map.py b/src/sage/combinat/combinatorial_map.py index e88714e1cab..477121a3cd2 100644 --- a/src/sage/combinat/combinatorial_map.py +++ b/src/sage/combinat/combinatorial_map.py @@ -131,7 +131,7 @@ def __init__(self, f, order=None, name=None): """ import types if not isinstance(f, types.FunctionType): - raise ValueError, "Only plain functions are supported" + raise ValueError("Only plain functions are supported") self._f = f self._order = order self._name = name diff --git a/src/sage/combinat/composition.py b/src/sage/combinat/composition.py index 9b42162336d..3f58ba0bd9b 100644 --- a/src/sage/combinat/composition.py +++ b/src/sage/combinat/composition.py @@ -1733,7 +1733,7 @@ def from_subset(self, S, n): return self.element_class(self, [n]) if n <= d[-1]: - raise ValueError, "S (=%s) is not a subset of {1, ..., %s}" % (d,n-1) + raise ValueError("S (=%s) is not a subset of {1, ..., %s}" % (d,n-1)) else: d.append(n) diff --git a/src/sage/combinat/composition_tableau.py b/src/sage/combinat/composition_tableau.py index 677fb8099c8..d98ae4d97d4 100644 --- a/src/sage/combinat/composition_tableau.py +++ b/src/sage/combinat/composition_tableau.py @@ -165,7 +165,7 @@ def __call__(self, *cell): try: return self[i][j] except IndexError: - raise IndexError, "The cell (%d,%d) is not contained in %s"%(i,j,self) + raise IndexError("The cell (%d,%d) is not contained in %s"%(i,j,self)) def pp(self): r""" diff --git a/src/sage/combinat/crystals/direct_sum.py b/src/sage/combinat/crystals/direct_sum.py index f201f3f287b..14e58179dbb 100644 --- a/src/sage/combinat/crystals/direct_sum.py +++ b/src/sage/combinat/crystals/direct_sum.py @@ -112,7 +112,7 @@ def __init__(self, crystals, **options): self._keepkey = keepkey self.crystals = crystals if len(crystals) == 0: - raise ValueError, "The direct sum is empty" + raise ValueError("The direct sum is empty") else: assert(crystal.cartan_type() == crystals[0].cartan_type() for crystal in crystals) self._cartan_type = crystals[0].cartan_type() diff --git a/src/sage/combinat/crystals/fast_crystals.py b/src/sage/combinat/crystals/fast_crystals.py index f504b54ee65..b61372775b4 100644 --- a/src/sage/combinat/crystals/fast_crystals.py +++ b/src/sage/combinat/crystals/fast_crystals.py @@ -98,7 +98,7 @@ def __classcall__(cls, cartan_type, shape, format = "string"): cartan_type = CartanType(cartan_type) shape = tuple(shape) if len(shape) > 2: - raise ValueError, "The shape must have length <=2" + raise ValueError("The shape must have length <=2") shape = shape + (0,)*(2-len(shape)) return super(FastCrystal, cls).__classcall__(cls, cartan_type, shape, format) diff --git a/src/sage/combinat/crystals/littelmann_path.py b/src/sage/combinat/crystals/littelmann_path.py index 74e87671f0a..81da4880bf7 100644 --- a/src/sage/combinat/crystals/littelmann_path.py +++ b/src/sage/combinat/crystals/littelmann_path.py @@ -181,7 +181,7 @@ def __init__(self, starting_weight): self.R = RootSystem(cartan_type) self.weight = starting_weight if not self.weight.parent().base_ring().has_coerce_map_from(QQ): - raise ValueError, "Please use the weight space, rather than weight lattice for your weights" + raise ValueError("Please use the weight space, rather than weight lattice for your weights") self._cartan_type = cartan_type self._name = "The crystal of LS paths of type %s and weight %s"%(cartan_type,starting_weight) if cartan_type.is_affine(): diff --git a/src/sage/combinat/crystals/tensor_product.py b/src/sage/combinat/crystals/tensor_product.py index cb7cc8bfd13..dcbef343ced 100644 --- a/src/sage/combinat/crystals/tensor_product.py +++ b/src/sage/combinat/crystals/tensor_product.py @@ -688,7 +688,7 @@ def __init__(self, crystals, **options): self._cartan_type = CartanType(options['cartan_type']) else: if len(crystals) == 0: - raise ValueError, "you need to specify the Cartan type if the tensor product list is empty" + raise ValueError("you need to specify the Cartan type if the tensor product list is empty") else: self._cartan_type = crystals[0].cartan_type() self.cartesian_product = CartesianProduct(*self.crystals) diff --git a/src/sage/combinat/designs/covering_design.py b/src/sage/combinat/designs/covering_design.py index 5f6f9f15a01..78d21fe2ebf 100644 --- a/src/sage/combinat/designs/covering_design.py +++ b/src/sage/combinat/designs/covering_design.py @@ -501,6 +501,6 @@ def best_known_covering_design_www(v, k, t, verbose=False): if 'covering not in database' in s: #not found str = "no (%d,%d,%d) covering design in database\n"%(v,k,t) - raise ValueError, str + raise ValueError(str) return sage_eval(s) diff --git a/src/sage/combinat/designs/ext_rep.py b/src/sage/combinat/designs/ext_rep.py index 48b43fea3a9..703adcbfc11 100644 --- a/src/sage/combinat/designs/ext_rep.py +++ b/src/sage/combinat/designs/ext_rep.py @@ -503,7 +503,7 @@ def check_dtrs_protocols(input_name, input_pv): ipv_major, ipv_minor = input_pv.split('.') if ppv_major != ipv_major or int(ppv_minor) < int(ipv_minor): msg = ('''Incompatible dtrs_protocols: program: %s %s: %s''' % (program_pv, input_name, input_pv)) - raise RuntimeError, msg + raise RuntimeError(msg) def open_extrep_file(fname): """ @@ -717,7 +717,7 @@ def __getattr__(self, attr): return grandchild msg = '"%s" is not found in attributes of %s or its children.' % \ (attr, self) - raise AttributeError, msg + raise AttributeError(msg) def __getitem__(self, i): """ @@ -742,7 +742,7 @@ def __getitem__(self, i): try: child = self.xt_children[i] except IndexError: - raise IndexError('{} has no index {}'.format(self.__repr__(), i)) + raise IndexError('%s no index %s' % (self.__repr__(), `i`)) if type(child) == TupleType: name, attributes, children = child if len(attributes) > 0: @@ -901,7 +901,7 @@ def _end_element(self, name): elif children[0][0] == 'd': convert = float else: - raise NotImplementedError, 'rational numbers' + raise NotImplementedError('rational numbers') ps = [] for x in children: ps.append(convert(''.join(x[2]))) diff --git a/src/sage/combinat/e_one_star.py b/src/sage/combinat/e_one_star.py index 9bf67d2f236..65dd8b9b47c 100644 --- a/src/sage/combinat/e_one_star.py +++ b/src/sage/combinat/e_one_star.py @@ -281,7 +281,7 @@ def __init__(self, v, t, color=None): self._vector.set_immutable() if not((t in ZZ) and 1 <= t <= len(v)): - raise ValueError, 'The type must be an integer between 1 and len(v)' + raise ValueError('The type must be an integer between 1 and len(v)') self._type = t if color is None: @@ -511,7 +511,7 @@ def _plot(self, projmat, face_contour, opacity): thickness=1, rgbcolor=self.color()) else: - raise NotImplementedError, "Plotting is implemented only for patches in two or three dimensions." + raise NotImplementedError("Plotting is implemented only for patches in two or three dimensions.") return G @@ -1068,7 +1068,7 @@ def repaint(self, cmap='Set1'): f.color(cmap(i/dim)[:3]) else: - raise TypeError, "Type of cmap (=%s) must be dict, list or str" %cmap + raise TypeError("Type of cmap (=%s) must be dict, list or str" %cmap) def plot(self, projmat=None, opacity=0.75): r""" @@ -1137,7 +1137,7 @@ def plot(self, projmat=None, opacity=0.75): return G else: - raise NotImplementedError, "Plotting is implemented only for patches in two or three dimensions." + raise NotImplementedError("Plotting is implemented only for patches in two or three dimensions.") def plot3d(self): r""" @@ -1163,7 +1163,7 @@ def plot3d(self): sage: P.plot3d() #not tested """ if self.dimension() != 3: - raise NotImplementedError, "3D plotting is implemented only for patches in three dimensions." + raise NotImplementedError("3D plotting is implemented only for patches in three dimensions.") face_list = [face._plot3d(self._face_contour) for face in self] G = sum(face_list) @@ -1285,7 +1285,7 @@ def plot_tikz(self, projmat=None, print_tikz_env=True, edgecolor='black', \end{tikzpicture} """ if self.dimension() != 3: - raise NotImplementedError, "Tikz Plotting is implemented only for patches in three dimensions." + raise NotImplementedError("Tikz Plotting is implemented only for patches in three dimensions.") if projmat == None: projmat = matrix(2, [-1.7320508075688772*0.5, 1.7320508075688772*0.5, 0, -0.5, -0.5, 1])*scale @@ -1388,17 +1388,17 @@ def __init__(self, sigma, method='suffix'): E_1^*(1->12, 2->13, 3->1) """ if not isinstance(sigma, WordMorphism): - raise TypeError, "sigma (=%s) must be an instance of WordMorphism"%sigma + raise TypeError("sigma (=%s) must be an instance of WordMorphism"%sigma) if sigma.domain().alphabet() != sigma.codomain().alphabet(): - raise ValueError, "The domain and codomain of (%s) must be the same."%sigma + raise ValueError("The domain and codomain of (%s) must be the same."%sigma) if abs(det(matrix(sigma))) != 1: - raise ValueError, "The substitution (%s) must be unimodular."%sigma + raise ValueError("The substitution (%s) must be unimodular."%sigma) first_letter = sigma.codomain().alphabet()[0] if not (first_letter in ZZ) or (first_letter < 1): - raise ValueError, "The substitution (%s) must be defined on positive integers."%sigma + raise ValueError("The substitution (%s) must be defined on positive integers."%sigma) self._sigma = WordMorphism(sigma) self._d = self._sigma.domain().size_of_alphabet() @@ -1415,7 +1415,7 @@ def __init__(self, sigma, method='suffix'): elif method == 'prefix': image_word = subst_im[:n] else: - raise ValueError, "Option 'method' can only be 'prefix' or 'suffix'." + raise ValueError("Option 'method' can only be 'prefix' or 'suffix'.") if not letter in X: X[letter] = [] v = self.inverse_matrix()*vector(image_word.parikh_vector()) @@ -1484,7 +1484,7 @@ def __call__(self, patch, iterations=1): if iterations == 0: return Patch(patch) elif iterations < 0: - raise ValueError, "iterations (=%s) must be >= 0." % iterations + raise ValueError("iterations (=%s) must be >= 0." % iterations) else: old_faces = patch for i in xrange(iterations): @@ -1520,7 +1520,7 @@ def __mul__(self, other): E_1^*(1->1, 2->1132, 3->1311) """ if not isinstance(other, E1Star): - raise TypeError, "other (=%s) must be an instance of E1Star" % other + raise TypeError("other (=%s) must be an instance of E1Star" % other) return E1Star(other.sigma() * self.sigma()) def __repr__(self): @@ -1561,7 +1561,7 @@ def _call_on_face(self, face, color=None): [[(3, 0, -3), 1]*, [(2, 1, -3), 2]*, [(2, 0, -2), 3]*] """ if len(face.vector()) != self._d: - raise ValueError, "The dimension of the faces must be equal to the size of the alphabet of the substitution." + raise ValueError("The dimension of the faces must be equal to the size of the alphabet of the substitution.") x_new = self.inverse_matrix() * face.vector() t = face.type() return (Face(x_new + v, k, color=color) for v, k in self._base_iter[t]) diff --git a/src/sage/combinat/finite_state_machine.py b/src/sage/combinat/finite_state_machine.py index a16a6391648..1f2a5283e51 100644 --- a/src/sage/combinat/finite_state_machine.py +++ b/src/sage/combinat/finite_state_machine.py @@ -522,7 +522,7 @@ def __init__(self, label, word_out=None, 'final' """ if label is None or label == "": - raise ValueError, "You have to specify a label for the state." + raise ValueError("You have to specify a label for the state.") self._label_ = label if isinstance(word_out, list): @@ -538,7 +538,7 @@ def __init__(self, label, word_out=None, if hasattr(hook, '__call__'): self.hook = hook else: - raise TypeError, 'Wrong argument for hook.' + raise TypeError('Wrong argument for hook.') def __lt__(self, other): @@ -905,7 +905,7 @@ def __init__(self, from_state, to_state, if hasattr(hook, '__call__'): self.hook = hook else: - raise TypeError, 'Wrong argument for hook.' + raise TypeError('Wrong argument for hook.') def __lt__(self, other): @@ -1032,7 +1032,7 @@ def __hash__(self): TypeError: Transitions are mutable, and thus not hashable. """ - raise TypeError, "Transitions are mutable, and thus not hashable." + raise TypeError("Transitions are mutable, and thus not hashable.") def _repr_(self): @@ -1110,8 +1110,8 @@ def __eq__(left, right): True """ if not is_FSMTransition(right): - raise TypeError, 'Only instances of FSMTransition ' \ - 'can be compared.' + raise TypeError('Only instances of FSMTransition ' \ + 'can be compared.') return left.from_state == right.from_state \ and left.to_state == right.to_state \ and left.word_in == right.word_in \ @@ -1465,16 +1465,16 @@ def __init__(self, if initial_states is not None: if not hasattr(initial_states, '__iter__'): - raise TypeError, 'Initial states must be iterable ' \ - '(e.g. a list of states).' + raise TypeError('Initial states must be iterable ' \ + '(e.g. a list of states).') for s in initial_states: state = self.add_state(s) state.is_initial = True if final_states is not None: if not hasattr(final_states, '__iter__'): - raise TypeError, 'Final states must be iterable ' \ - '(e.g. a list of states).' + raise TypeError('Final states must be iterable ' \ + '(e.g. a list of states).') for s in final_states: state = self.add_state(s) state.is_final = True @@ -1513,7 +1513,7 @@ def __init__(self, L = [sf, transition] self.add_transition(L) else: - raise TypeError, 'Wrong input data for transition.' + raise TypeError('Wrong input data for transition.') if determine_alphabets is None and input_alphabet is None \ and output_alphabet is None: determine_alphabets = True @@ -1528,14 +1528,14 @@ def __init__(self, elif hasattr(transition, '__iter__'): self.add_transition(transition) else: - raise TypeError, 'Wrong input data for transition.' + raise TypeError('Wrong input data for transition.') if determine_alphabets is None and input_alphabet is None \ and output_alphabet is None: determine_alphabets = True elif hasattr(data, '__call__'): self.add_from_transition_function(data) else: - raise TypeError, 'Cannot decide what to do with data.' + raise TypeError('Cannot decide what to do with data.') if determine_alphabets: self.determine_alphabets() @@ -1707,8 +1707,8 @@ def __hash__(self): """ if getattr(self, "_immutable", False): return hash((tuple(self.states()), tuple(self.transitions()))) - raise TypeError, "Finite state machines are mutable, " \ - "and thus not hashable." + raise TypeError("Finite state machines are mutable, " \ + "and thus not hashable.") #************************************************************************* @@ -1804,12 +1804,12 @@ def __call__(self, *args, **kwargs): [('A', 1), ('B', 1), ('B', 2)] """ if len(args) == 0: - raise TypeError, "Called with too few arguments." + raise TypeError("Called with too few arguments.") if is_FiniteStateMachine(args[0]): return self.composition(*args, **kwargs) if hasattr(args[0], '__iter__'): return self.process(*args, **kwargs) - raise TypeError, "Do not know what to do with that arguments." + raise TypeError("Do not know what to do with that arguments.") #************************************************************************* @@ -1860,8 +1860,8 @@ def __eq__(left, right): False """ if not is_FiniteStateMachine(right): - raise TypeError, 'Only instances of FiniteStateMachine ' \ - 'can be compared.' + raise TypeError('Only instances of FiniteStateMachine ' \ + 'can be compared.') if len(left._states_) != len(right._states_): return False for state in left.iter_states(): @@ -2534,8 +2534,7 @@ def what(s, switch): return s except KeyError: pass - raise LookupError, \ - "No state with label %s found." % (what(state, switch),) + raise LookupError("No state with label %s found." % (what(state, switch),)) def transition(self, transition): @@ -2570,7 +2569,7 @@ def transition(self, transition): for s in self.iter_transitions(transition.from_state): if s == transition: return s - raise LookupError, "No transition found." + raise LookupError("No transition found.") #************************************************************************* @@ -2629,7 +2628,7 @@ def has_transition(self, transition): """ if is_FSMTransition(transition): return transition in self.iter_transitions() - raise TypeError, "Transition is not an instance of FSMTransition." + raise TypeError("Transition is not an instance of FSMTransition.") def has_initial_state(self, state): @@ -3014,7 +3013,7 @@ def add_transition(self, *args, **kwargs): args = d kwargs = {} else: - raise TypeError, "Cannot decide what to do with input." + raise TypeError("Cannot decide what to do with input.") data = dict(zip( ('from_state', 'to_state', 'word_in', 'word_out', 'hook'), @@ -3152,7 +3151,7 @@ def add_from_transition_function(self, function, initial_states=None, TypeError: mutable vectors are unhashable """ if self.input_alphabet is None: - raise ValueError, ("No input alphabet is given. " + raise ValueError("No input alphabet is given. " "Try calling determine_alphabets().") if initial_states is None: @@ -3164,10 +3163,10 @@ def add_from_transition_function(self, function, initial_states=None, state.is_initial = True not_done.append(state) else: - raise TypeError, 'Initial states must be iterable ' \ - '(e.g. a list of states).' + raise TypeError('Initial states must be iterable ' \ + '(e.g. a list of states).') if len(not_done) == 0: - raise ValueError, "No state is initial." + raise ValueError("No state is initial.") if explore_existing_states: ignore_done = self.states() for s in not_done: @@ -3790,7 +3789,7 @@ def composition(self, other, algorithm=None, elif algorithm == 'explorative': return self._composition_explorative_(other) else: - raise ValueError, "Unknown algorithm %s." % (algorithm,) + raise ValueError("Unknown algorithm %s." % (algorithm,)) def _composition_direct_(self, other, only_accessible_components=True): @@ -4385,9 +4384,9 @@ def quotient(self, classes): state_mapping[transition.to_state], transition.word_in, transition.word_out)) except LookupError: - raise ValueError, "There is a transition %s in the " \ + raise ValueError("There is a transition %s in the " \ "original transducer, but no corresponding " \ - "transition in the new transducer." % transition + "transition in the new transducer." % transition) return new @@ -4433,7 +4432,7 @@ def graph(self, edge_labels='words_in_out'): elif hasattr(edge_labels, '__call__'): label_fct = edge_labels else: - raise TypeError, 'Wrong argument for edge_labels.' + raise TypeError('Wrong argument for edge_labels.') graph_data = [] isolated_vertices = [] @@ -4822,7 +4821,7 @@ def minimization(self, algorithm=None): elif algorithm == "Brzozowski" or (algorithm is None and not deterministic): return self._minimization_Brzozowski_() else: - raise NotImplementedError, "Algorithm '%s' is not implemented. Choose 'Moore' or 'Brzozowski'" % algorithm + raise NotImplementedError("Algorithm '%s' is not implemented. Choose 'Moore' or 'Brzozowski'" % algorithm) def _minimization_Brzozowski_(self): @@ -5162,9 +5161,9 @@ def __init__(self, fsm, input_tape=None, initial_state=None): try: self.current_state = fsm_initial_states[0] except IndexError: - raise ValueError, "No state is initial." + raise ValueError("No state is initial.") if len(fsm_initial_states) > 1: - raise ValueError, "Several initial states." + raise ValueError("Several initial states.") else: self.current_state = initial_state self.output_tape = [] @@ -5174,7 +5173,7 @@ def __init__(self, fsm, input_tape=None, initial_state=None): if hasattr(input_tape, '__iter__'): self._input_tape_iter_ = iter(input_tape) else: - raise ValueError, "Given input tape is not iterable." + raise ValueError("Given input tape is not iterable.") def __iter__(self): """ diff --git a/src/sage/combinat/free_module.py b/src/sage/combinat/free_module.py index e3c446d8b4c..4013e374cce 100644 --- a/src/sage/combinat/free_module.py +++ b/src/sage/combinat/free_module.py @@ -942,7 +942,7 @@ def _divide_if_possible(x, y): """ q, r = x.quo_rem(y) if r != 0: - raise ValueError, "%s is not divisible by %s"%(x, y) + raise ValueError("%s is not divisible by %s"%(x, y)) else: return q @@ -1287,7 +1287,7 @@ def __init__(self, R, basis_keys, element_class = None, category = None, **kwds) #Make sure R is a ring with unit element from sage.categories.all import Rings if R not in Rings(): - raise TypeError, "Argument R must be a ring." + raise TypeError("Argument R must be a ring.") if category is None: category = ModulesWithBasis(R) @@ -1530,7 +1530,7 @@ def _element_constructor_(self, x): if x == 0: return self.zero() else: - raise TypeError, "do not know how to make x (= %s) an element of %s"%(x, self) + raise TypeError("do not know how to make x (= %s) an element of %s"%(x, self)) #x is an element of the basis enumerated set; # This is a very ugly way of testing this elif ((hasattr(self._basis_keys, 'element_class') and @@ -1546,7 +1546,7 @@ def _element_constructor_(self, x): return self._coerce_end(x) except TypeError: pass - raise TypeError, "do not know how to make x (= %s) an element of self (=%s)"%(x,self) + raise TypeError("do not know how to make x (= %s) an element of self (=%s)"%(x,self)) def _an_element_impl(self): """ @@ -1747,7 +1747,7 @@ def print_options(self, **kwds): ]: self._print_options[option] = kwds[option] else: - raise ValueError, '%s is not a valid print option.' % option + raise ValueError('%s is not a valid print option.' % option) else: return self._print_options diff --git a/src/sage/combinat/graph_path.py b/src/sage/combinat/graph_path.py index a72cecc211c..b7830aad2bb 100644 --- a/src/sage/combinat/graph_path.py +++ b/src/sage/combinat/graph_path.py @@ -88,25 +88,25 @@ class contains all of the paths from source to target. TypeError: g must be a directed acyclic graph """ if not isinstance(g, digraph.DiGraph): - raise TypeError, "g must be a DiGraph" + raise TypeError("g must be a DiGraph") elif not g.is_directed_acyclic(): - raise TypeError, "g must be a directed acyclic graph" + raise TypeError("g must be a directed acyclic graph") if source is None and target is None: return GraphPaths_all(g) elif source is not None and target is None: if source not in g: - raise ValueError, "source must be in g" + raise ValueError("source must be in g") return GraphPaths_s(g, source) elif source is None and target is not None: if target not in g: - raise ValueError, "target must be in g" + raise ValueError("target must be in g") return GraphPaths_t(g, target) else: if source not in g: - raise ValueError, "source must be in g" + raise ValueError("source must be in g") if target not in g: - raise ValueError, "target must be in g" + raise ValueError("target must be in g") return GraphPaths_st(g, source, target) class GraphPaths_common: diff --git a/src/sage/combinat/integer_vector.py b/src/sage/combinat/integer_vector.py index 51fbac93ecc..ae01beee39f 100644 --- a/src/sage/combinat/integer_vector.py +++ b/src/sage/combinat/integer_vector.py @@ -614,7 +614,7 @@ def list(self): ... NotImplementedError: infinite list """ - raise NotImplementedError, "infinite list" # can't use InfiniteAbstractCombinatorialClass + raise NotImplementedError("infinite list") # can't use InfiniteAbstractCombinatorialClass def cardinality(self): """ @@ -812,7 +812,7 @@ def rank(self, x): """ if x not in self: - raise ValueError, "argument is not a member of IntegerVectors(%d,%d)" % (self.n, self.k) + raise ValueError("argument is not a member of IntegerVectors(%d,%d)" % (self.n, self.k)) n = self.n k = self.k @@ -1126,7 +1126,7 @@ def list(self): NotImplementedError: infinite list """ if 'max_length' not in self.constraints: - raise NotImplementedError, "infinite list" # no list from infinite iter + raise NotImplementedError("infinite list") # no list from infinite iter else: return list(self) diff --git a/src/sage/combinat/integer_vectors_mod_permgroup.py b/src/sage/combinat/integer_vectors_mod_permgroup.py index d9f73486243..2f3ad42362d 100644 --- a/src/sage/combinat/integer_vectors_mod_permgroup.py +++ b/src/sage/combinat/integer_vectors_mod_permgroup.py @@ -473,7 +473,7 @@ def __call__(self, v, check=True): if v.parent() is self: return v else: - raise ValueError, '%s shoud be a Python list of integer'%(v) + raise ValueError('%s shoud be a Python list of integer'%(v)) except Exception: return self.element_class(self, list(v), check=check) @@ -719,7 +719,7 @@ def __call__(self, v, check=True): if v.parent() is self: return v else: - raise ValueError, '%s shoud be a Python list of integer'%(v) + raise ValueError('%s shoud be a Python list of integer'%(v)) except Exception: return self.element_class(self, list(v), check=check) diff --git a/src/sage/combinat/k_tableau.py b/src/sage/combinat/k_tableau.py index aee089c604e..0916f4a221c 100644 --- a/src/sage/combinat/k_tableau.py +++ b/src/sage/combinat/k_tableau.py @@ -200,7 +200,7 @@ def WeakTableau(t, k, inner_shape = [], representation = "core"): elif representation == "factorized_permutation": return WeakTableau_factorized_permutation(t, k, inner_shape = inner_shape) else: - raise NotImplementedError, "The representation option needs to be 'core', 'bounded', or 'factorized_permuation'" + raise NotImplementedError("The representation option needs to be 'core', 'bounded', or 'factorized_permuation'") def WeakTableaux(k, shape , weight, representation = "core"): r""" @@ -264,7 +264,7 @@ def WeakTableaux(k, shape , weight, representation = "core"): elif representation == "factorized_permutation": return WeakTableaux_factorized_permutation(k, shape, weight) else: - raise NotImplementedError, "The representation option needs to be 'core', 'bounded', or 'factorized_permuation'" + raise NotImplementedError("The representation option needs to be 'core', 'bounded', or 'factorized_permuation'") #Abstract class for the elements of weak tableau class WeakTableau_abstract(ClonableList): @@ -1382,7 +1382,7 @@ def __classcall_private__(cls, t, k): inner = tab.inner_shape() weight = tuple(tab.weight()) if outer.conjugate().length() > k: - raise ValueError, "The shape of %s is not %s-bounded"%(t, k) + raise ValueError("The shape of %s is not %s-bounded"%(t, k)) return WeakTableaux_bounded(k, [outer, inner], weight)(t) def __init__(self, parent, t): @@ -1426,7 +1426,7 @@ def __init__(self, parent, t): self.k = k self._list = [r for r in t] if parent._outer_shape.conjugate().length() > k: - raise ValueError, "%s is not a %s-bounded tableau"%(t, k) + raise ValueError("%s is not a %s-bounded tableau"%(t, k)) ClonableList.__init__(self, parent, t) def _repr_diagram(self): @@ -1805,7 +1805,7 @@ def straighten_input(t, k): if isinstance(t[0], list) or isinstance(t[0], tuple): w_tuple = tuple(W.from_reduced_word(p) for p in t) elif t[0] not in W: - raise ValueError, "The input must be a list of reduced words or Weyl group elements" + raise ValueError("The input must be a list of reduced words or Weyl group elements") else: w_tuple = tuple(W(r) for r in t) else: diff --git a/src/sage/combinat/knutson_tao_puzzles.py b/src/sage/combinat/knutson_tao_puzzles.py index 8b6f51aed62..2cbd977dadc 100644 --- a/src/sage/combinat/knutson_tao_puzzles.py +++ b/src/sage/combinat/knutson_tao_puzzles.py @@ -1587,7 +1587,7 @@ def __classcall_private__(cls, puzzle_pieces, max_letter=None): if max_letter is not None: puzzle_pieces = BK_pieces(max_letter) else: - raise ValueError, "max_letter needs to be specified" + raise ValueError("max_letter needs to be specified") return super(KnutsonTaoPuzzleSolver, cls).__classcall__(cls, puzzle_pieces) def __call__(self, lamda, mu, algorithm='strips'): diff --git a/src/sage/combinat/ncsf_qsym/qsym.py b/src/sage/combinat/ncsf_qsym/qsym.py index a7c626d4c79..930398bb1ed 100644 --- a/src/sage/combinat/ncsf_qsym/qsym.py +++ b/src/sage/combinat/ncsf_qsym/qsym.py @@ -1451,7 +1451,7 @@ def to_symmetric_function(self): M = self.parent().realization_of().Monomial() return M( self ).to_symmetric_function() else: - raise ValueError, "%s is not a symmetric function"%self + raise ValueError("%s is not a symmetric function"%self) class Monomial(CombinatorialFreeModule, BindableClass): r""" @@ -1921,7 +1921,7 @@ def to_symmetric_function(self): return m.sum_of_terms([(I, coeff) for (I, coeff) in self if list(I) in _Partitions], distinct=True) else: - raise ValueError, "%s is not a symmetric function"%self + raise ValueError("%s is not a symmetric function"%self) M = Monomial diff --git a/src/sage/combinat/permutation.py b/src/sage/combinat/permutation.py index 73637289976..95640fe17f4 100644 --- a/src/sage/combinat/permutation.py +++ b/src/sage/combinat/permutation.py @@ -4007,7 +4007,7 @@ def shifted_concatenation(self, other, side = "right"): elif side == "left" : return Permutation([a + len(self) for a in other] + list(self)) else : - raise ValueError, "%s must be \"left\" or \"right\"" %(side) + raise ValueError("%s must be \"left\" or \"right\"" %(side)) def shifted_shuffle(self, other): r""" diff --git a/src/sage/combinat/posets/lattices.py b/src/sage/combinat/posets/lattices.py index ed0f131d20a..5daa71a206f 100644 --- a/src/sage/combinat/posets/lattices.py +++ b/src/sage/combinat/posets/lattices.py @@ -67,7 +67,7 @@ def MeetSemilattice(data, *args, **options): return data P = Poset(data, *args, **options) if not P.is_meet_semilattice(): - raise ValueError, "Not a meet semilattice." + raise ValueError("Not a meet semilattice.") return FiniteMeetSemilattice(P) class FiniteMeetSemilattice(FinitePoset): @@ -191,7 +191,7 @@ def JoinSemilattice(data, *args, **options): return data P = Poset(data, *args, **options) if not P.is_join_semilattice(): - raise ValueError, "Not a join semilattice." + raise ValueError("Not a join semilattice.") return FiniteJoinSemilattice(P) class FiniteJoinSemilattice(FinitePoset): @@ -328,7 +328,7 @@ def LatticePoset(data, *args, **options): return data P = Poset(data, *args, **options) if not P.is_lattice(): - raise ValueError, "Not a lattice." + raise ValueError("Not a lattice.") return FiniteLatticePoset(P, category = FiniteLatticePosets(), facade = P._is_facade) diff --git a/src/sage/combinat/posets/linear_extensions.py b/src/sage/combinat/posets/linear_extensions.py index 3d88cf5bc2e..e5a06416ab1 100644 --- a/src/sage/combinat/posets/linear_extensions.py +++ b/src/sage/combinat/posets/linear_extensions.py @@ -139,7 +139,7 @@ def check(self): """ P = self.parent().poset() if not P.is_linear_extension(self): - raise ValueError, "%s is not a linear extension of %s"%(self, P) + raise ValueError("%s is not a linear extension of %s"%(self, P)) def poset(self): r""" @@ -672,7 +672,7 @@ def _element_constructor_(self, lst, check=True): [4, 3, 2, 1] """ if not isinstance(lst, (list, tuple)): - raise TypeError, "Input should be a list or tuple." + raise TypeError("Input should be a list or tuple.") lst = map(self._poset, lst) if self._is_facade: return lst diff --git a/src/sage/combinat/posets/posets.py b/src/sage/combinat/posets/posets.py index 9e83d36d14c..c91c38a5c89 100644 --- a/src/sage/combinat/posets/posets.py +++ b/src/sage/combinat/posets/posets.py @@ -511,7 +511,7 @@ def Poset(data=None, element_labels=None, cover_relations=False, linear_extensio try: u, v = r except ValueError: - raise TypeError, "not a list of relations" + raise TypeError("not a list of relations") D = DiGraph() D.add_vertices(elements) D.add_edges(relations) @@ -519,11 +519,11 @@ def Poset(data=None, element_labels=None, cover_relations=False, linear_extensio # type 3, list/tuple of upper covers D = DiGraph(dict([[Integer(i),data[i]] for i in range(len(data))])) else: - raise ValueError, "not valid poset data." + raise ValueError("not valid poset data.") # DEBUG: At this point D should be a DiGraph. if not isinstance(D,DiGraph): - raise TypeError, "BUG: D should be a digraph." + raise TypeError("BUG: D should be a digraph.") # Determine cover relations, if necessary. if cover_relations is False: @@ -532,11 +532,11 @@ def Poset(data=None, element_labels=None, cover_relations=False, linear_extensio # Check that the digraph does not contain loops, multiple edges # and is transitively reduced. if D.has_loops(): - raise ValueError, "Hasse diagram contains loops." + raise ValueError("Hasse diagram contains loops.") elif D.has_multiple_edges(): - raise ValueError, "Hasse diagram contains multiple edges." + raise ValueError("Hasse diagram contains multiple edges.") elif cover_relations is True and not D.is_transitively_reduced(): - raise ValueError, "Hasse diagram is not transitively reduced." + raise ValueError("Hasse diagram is not transitively reduced.") if linear_extension and elements is not None: lin_ext = list(elements) @@ -545,7 +545,7 @@ def Poset(data=None, element_labels=None, cover_relations=False, linear_extensio try: lin_ext = D.topological_sort() except Exception: - raise ValueError, "Hasse diagram contains cycles." + raise ValueError("Hasse diagram contains cycles.") # Relabel using the linear_extension. # So range(len(D)) becomes a linear extension of the poset. @@ -881,7 +881,7 @@ def _element_to_vertex(self, element): try: return self._element_to_vertex_dict[element] except KeyError: - raise ValueError, "element (=%s) not in poset"%element + raise ValueError("element (=%s) not in poset"%element) def _vertex_to_element(self, vertex): """ @@ -1041,7 +1041,7 @@ def _element_constructor_(self, element): return self.element_class(self, \ self._elements[element], self.cardinality()+element) else: - raise ValueError, "%s is not an element of this poset"%type(element) + raise ValueError("%s is not an element of this poset"%type(element)) def __call__(self, element): """ @@ -2207,7 +2207,7 @@ def rank(self, element=None): elif self.is_ranked(): return self.rank_function()(element) else: - raise ValueError, "Poset is not ranked." + raise ValueError("Poset is not ranked.") def is_ranked(self): r""" @@ -2641,7 +2641,7 @@ def is_isomorphic(self,other): if hasattr(other,'hasse_diagram'): return self.hasse_diagram().is_isomorphic( other.hasse_diagram() ) else: - raise ValueError, 'The input is not a finite poset.' + raise ValueError('The input is not a finite poset.') import __builtin__ # Caveat: list is overridden by the method list above!!! def antichains(self, element_constructor = __builtin__.list): diff --git a/src/sage/combinat/root_system/branching_rules.py b/src/sage/combinat/root_system/branching_rules.py index 43dfb12a379..bead7ffe8e0 100644 --- a/src/sage/combinat/root_system/branching_rules.py +++ b/src/sage/combinat/root_system/branching_rules.py @@ -983,7 +983,7 @@ def rule(x): rule = branching_rule(R._cartan_type, S._cartan_type, rule) if hasattr(rule,"_S"): if rule._S != S.cartan_type(): - raise ValueError,"rule has wrong target Cartan type" + raise ValueError("rule has wrong target Cartan type") mdict = {} for k in chi.weight_multiplicities(): # TODO: Could this use the new from_vector of ambient_space ? @@ -1120,7 +1120,7 @@ def __mul__(self, other): f = lambda x : other._f(self._f(x)) return BranchingRule(self._R, other._S, f, "composite", intermediate_types=intermediates, intermediate_names=internames) else: - raise ValueError, "unable to define composite: source and target don't agree" + raise ValueError("unable to define composite: source and target don't agree") def Rtype(self): """ @@ -1180,7 +1180,7 @@ def describe(self, verbose=False, debug=False, no_r=False): Rspace = RootSystem(self._R).ambient_space() Sspace = RootSystem(self._S).ambient_space() if self._R.is_compound(): - raise ValueError,"Cannot describe branching rule from reducible type" + raise ValueError("Cannot describe branching rule from reducible type") if not no_r: print "\n%s"%(self._R.affine().dynkin_diagram()).__repr__() if self._S.is_compound(): @@ -1370,7 +1370,7 @@ def br(x): raise ValueError("No default rule found (you must specify the rule)") elif rule == "identity": if Rtype is not Stype: - raise ValueError, "Cartan types must match for identity rule" + raise ValueError("Cartan types must match for identity rule") return BranchingRule(Rtype, Stype, lambda x : x, "identity") elif rule == "levi": if not s == r-1: diff --git a/src/sage/combinat/root_system/dynkin_diagram.py b/src/sage/combinat/root_system/dynkin_diagram.py index 55ec3f6ab4c..4b394a50bbf 100644 --- a/src/sage/combinat/root_system/dynkin_diagram.py +++ b/src/sage/combinat/root_system/dynkin_diagram.py @@ -678,23 +678,23 @@ def precheck(t, letter=None, length=None, affine=None, n_ge=None, n=None): """ if letter is not None: if t[0] != letter: - raise ValueError, "t[0] must be = '%s'"%letter + raise ValueError("t[0] must be = '%s'"%letter) if length is not None: if len(t) != length: - raise ValueError, "len(t) must be = %s"%length + raise ValueError("len(t) must be = %s"%length) if affine is not None: try: if t[2] != affine: - raise ValueError, "t[2] must be = %s"%affine + raise ValueError("t[2] must be = %s"%affine) except IndexError: - raise ValueError, "t[2] must be = %s"%affine + raise ValueError("t[2] must be = %s"%affine) if n_ge is not None: if t[1] < n_ge: - raise ValueError, "t[1] must be >= %s"%n_ge + raise ValueError("t[1] must be >= %s"%n_ge) if n is not None: if t[1] != n: - raise ValueError, "t[1] must be = %s"%n + raise ValueError("t[1] must be = %s"%n) diff --git a/src/sage/combinat/root_system/root_lattice_realizations.py b/src/sage/combinat/root_system/root_lattice_realizations.py index fc514e5f794..18b8a35ab49 100644 --- a/src/sage/combinat/root_system/root_lattice_realizations.py +++ b/src/sage/combinat/root_system/root_lattice_realizations.py @@ -358,9 +358,9 @@ def highest_root(self): """ if not self.root_system.is_finite(): - raise ValueError, "The root system of %s is not of finite Cartan type"%self + raise ValueError("The root system of %s is not of finite Cartan type"%self) if not self.root_system.is_irreducible(): - raise ValueError, "The root system of %s is reducible"%self + raise ValueError("The root system of %s is reducible"%self) return self.a_long_simple_root().to_dominant_chamber() @cached_method @@ -512,7 +512,7 @@ def positive_roots(self): successive reflections toward the positive chamber. """ if not self.cartan_type().is_finite(): - raise NotImplementedError, "Only implemented for finite Cartan type" + raise NotImplementedError("Only implemented for finite Cartan type") return TransitiveIdealGraded(attrcall('pred'), self.simple_roots()) @cached_method @@ -540,7 +540,7 @@ def positive_roots_by_height(self, increasing = True): """ if not self.cartan_type().is_finite(): - raise NotImplementedError, "Only implemented for finite Cartan type" + raise NotImplementedError("Only implemented for finite Cartan type") ranks = self.root_poset().level_sets() if not increasing: ranks.reverse() @@ -577,7 +577,7 @@ def positive_roots_parabolic(self, index_set = None): """ if not self.cartan_type().is_finite(): - raise NotImplementedError, "Only implemented for finite Cartan type" + raise NotImplementedError("Only implemented for finite Cartan type") if index_set is None: index_set = tuple(self.cartan_type().index_set()) @@ -614,7 +614,7 @@ def positive_roots_nonparabolic(self, index_set = None): """ if not self.cartan_type().is_finite(): - raise NotImplementedError, "Only implemented for finite Cartan type" + raise NotImplementedError("Only implemented for finite Cartan type") if index_set is None: index_set = tuple(self.cartan_type().index_set()) return [x for x in self.positive_roots() if not x.is_parabolic_root(index_set)] @@ -649,7 +649,7 @@ def positive_roots_nonparabolic_sum(self, index_set = None): """ if not self.cartan_type().is_finite(): - raise ValueError, "Cartan type %s is not finite"%(self.cartan_type()) + raise ValueError("Cartan type %s is not finite"%(self.cartan_type())) if index_set is None or index_set == tuple(self.cartan_type().index_set()): return self.zero() return sum(self.positive_roots_nonparabolic(index_set)) @@ -717,7 +717,7 @@ def almost_positive_roots(self): [-alpha[1], alpha[1], alpha[1] + alpha[2], -alpha[2], alpha[2]] """ if not self.cartan_type().is_finite(): - raise ValueError, "%s is not a finite Cartan type"%(self.cartan_type()) + raise ValueError("%s is not a finite Cartan type"%(self.cartan_type())) return sorted([ -beta for beta in self.simple_roots() ] + list(self.positive_roots())) def negative_roots(self): @@ -734,7 +734,7 @@ def negative_roots(self): """ if not self.cartan_type().is_finite(): - raise ValueError, "%s is not a finite Cartan type"%(self.cartan_type()) + raise ValueError("%s is not a finite Cartan type"%(self.cartan_type())) from sage.combinat.combinat import MapCombinatorialClass return MapCombinatorialClass(self.positive_roots(), attrcall('__neg__'), "The negative roots of %s"%self) # Todo: use this instead once TransitiveIdeal will be a proper enumerated set @@ -902,7 +902,7 @@ def null_coroot(self): alphacheck[0] + 2*alphacheck[1] + 3*alphacheck[2] + 2*alphacheck[3] + alphacheck[4] """ if not self.cartan_type().is_affine(): - raise ValueError, "%s is not an affine Cartan type"%(self.cartan_type()) + raise ValueError("%s is not an affine Cartan type"%(self.cartan_type())) coef = self.cartan_type().acheck() return sum(coef[k]*self.simple_coroots()[k] for k in coef.keys()) @@ -1144,7 +1144,7 @@ def simple_projections(self, to_negative=True): pi """ if to_negative is not True: - raise NotImplementedError, "only implemented when 'to_negative' is True" + raise NotImplementedError("only implemented when 'to_negative' is True") res = self.alpha().zip(self.projection, self.alphacheck()) # Should this use rename to set a nice name for this family? res.rename("pi") @@ -2490,9 +2490,9 @@ def _maximum_root_length(self): """ ct = self.cartan_type() if not ct.is_irreducible(): - raise NotImplementedError, "Implemented only for irreducible finite root systems" + raise NotImplementedError("Implemented only for irreducible finite root systems") if not ct.is_finite(): - raise NotImplementedError, "Implemented only for irreducible finite root systems" + raise NotImplementedError("Implemented only for irreducible finite root systems") L = self.root_system.ambient_space() # uses peculiarities of ambient embedding return max([root.scalar(root) for root in L.simple_roots()]) @@ -2784,16 +2784,16 @@ def to_dominant_chamber(self, index_set = None, positive = True, reduced_word = level = self.level() if level > 0: if not positive: - raise ValueError, "%s is not in the orbit of the fundamental chamber"%(self) + raise ValueError("%s is not in the orbit of the fundamental chamber"%(self)) elif level < 0: if positive: - raise ValueError, "%s is not in the orbit of the negative of the fundamental chamber"%(self) + raise ValueError("%s is not in the orbit of the negative of the fundamental chamber"%(self)) elif not (self == self.parent().zero()): # nonzero level zero weight if positive: - raise ValueError, "%s is not in the orbit of the fundamental chamber"%(self) + raise ValueError("%s is not in the orbit of the fundamental chamber"%(self)) else: - raise ValueError, "%s is not in the orbit of the negative of the fundamental chamber"%(self) + raise ValueError("%s is not in the orbit of the negative of the fundamental chamber"%(self)) if reduced_word: direction = [] while True: @@ -2991,7 +2991,7 @@ def level(self): 3 """ if not self.parent().cartan_type().is_affine(): - raise ValueError, "%s does not belong to a lattice of affine Cartan type"%self + raise ValueError("%s does not belong to a lattice of affine Cartan type"%self) return self.scalar(self.parent().null_coroot()) @cached_in_parent_method @@ -3071,7 +3071,7 @@ def to_simple_root(self, reduced_word=False): pass j = self.first_descent(positive=True) if j is None: - raise ValueError, "%s is not a positive root"%self + raise ValueError("%s is not a positive root"%self) result = self.simple_reflection(j).to_simple_root(reduced_word=reduced_word) if reduced_word: return (result[0], (j,) + result[1]) @@ -3137,7 +3137,7 @@ def translation(self, x): -Lambda[0] + 2*Lambda[2] """ if not self.level().is_zero(): - raise ValueError, "%s is not of level zero"%(self) + raise ValueError("%s is not of level zero"%(self)) return x + x.level() * self def weyl_action(self, element, inverse = False): @@ -3194,10 +3194,10 @@ def weyl_action(self, element, inverse = False): the_word = [x for x in element] I = self.parent().index_set() if not all(i in I for i in the_word): - raise ValueError, "Not all members of %s are in the index set of the %s"%(element, self.parent()) + raise ValueError("Not all members of %s are in the index set of the %s"%(element, self.parent())) else: if not isinstance(element, Element): - raise TypeError, "%s should be an element of a Coxeter group"%(element) + raise TypeError("%s should be an element of a Coxeter group"%(element)) W = element.parent() if W is self.parent().weyl_group(): # Action by an element of the Coxeter or Weyl group of ``self`` @@ -3207,7 +3207,7 @@ def weyl_action(self, element, inverse = False): else: # Action by an element of an isomorphic Coxeter or Weyl group if not (W in CoxeterGroups() and W.cartan_type() == self.parent().cartan_type()): - raise TypeError, "%s should be an element of a Coxeter group of type %s"%(element, self.parent().cartan_type()) + raise TypeError("%s should be an element of a Coxeter group of type %s"%(element, self.parent().cartan_type())) the_word = element.reduced_word() if inverse is False: the_word.reverse() @@ -3294,9 +3294,9 @@ def is_short_root(self): """ ct = self.parent().cartan_type() if not ct.is_irreducible(): - raise ValueError, "Cartan type needs to be irreducible!" + raise ValueError("Cartan type needs to be irreducible!") if not ct.is_finite(): - raise NotImplementedError, "Implemented only for irreducible finite root systems" + raise NotImplementedError("Implemented only for irreducible finite root systems") L = self.parent().root_system.ambient_space() # uses peculiarities of ambient embedding ls = L(self) return ls.scalar(ls) < L._maximum_root_length() diff --git a/src/sage/combinat/root_system/root_space.py b/src/sage/combinat/root_system/root_space.py index f33ff2098bc..5169d17bb55 100644 --- a/src/sage/combinat/root_system/root_space.py +++ b/src/sage/combinat/root_system/root_space.py @@ -187,7 +187,7 @@ def _to_root_lattice(self, x): try: return self.root_system.root_lattice().sum_of_terms( (i, ZZ(c)) for (i,c) in x) except TypeError: - raise ValueError, "%s does not have integral coefficients"%x + raise ValueError("%s does not have integral coefficients"%x) @cached_method def _to_classical_on_basis(self, i): @@ -244,7 +244,7 @@ def scalar(self, lambdacheck): """ # Find some better test if not (lambdacheck in self.parent().coroot_lattice() or lambdacheck in self.parent().coroot_space()): - raise TypeError, "%s is not in a coroot lattice/space"%(lambdacheck) + raise TypeError("%s is not in a coroot lattice/space"%(lambdacheck)) zero = self.parent().base_ring().zero() cartan_matrix = self.parent().dynkin_diagram() return sum( (sum( (lambdacheck[i]*s for i,s in cartan_matrix.column(j)), zero) * c for j,c in self), zero) @@ -371,9 +371,9 @@ def max_coroot_le(self): NotImplementedError: Only implemented for finite Cartan type """ if not self.parent().cartan_type().is_finite(): - raise NotImplementedError, "Only implemented for finite Cartan type" + raise NotImplementedError("Only implemented for finite Cartan type") if not self.is_positive_root(): - raise ValueError, "%s is not in the positive cone of roots"%(self) + raise ValueError("%s is not in the positive cone of roots"%(self)) coroots = self.parent().coroot_lattice().positive_roots_by_height(increasing=False) for beta in coroots: if beta.quantum_root(): diff --git a/src/sage/combinat/root_system/type_E.py b/src/sage/combinat/root_system/type_E.py index fac673c9763..364557183da 100644 --- a/src/sage/combinat/root_system/type_E.py +++ b/src/sage/combinat/root_system/type_E.py @@ -66,7 +66,7 @@ def __init__(self, root_system, baseRing): self.root(4,5,p1=1), self.root(5,6,p1=1)] else: - raise NotImplementedError, "Type \'E\' root systems only come in flavors 6, 7, 8. Please make another choice" + raise NotImplementedError("Type \'E\' root systems only come in flavors 6, 7, 8. Please make another choice") def dimension(self): """ diff --git a/src/sage/combinat/root_system/weyl_group.py b/src/sage/combinat/root_system/weyl_group.py index ff8911fa934..106ac83e4dd 100644 --- a/src/sage/combinat/root_system/weyl_group.py +++ b/src/sage/combinat/root_system/weyl_group.py @@ -363,7 +363,7 @@ def reflections(self): ret[r] = alp return Family(ret) except Exception: - raise NotImplementedError, "reflections are only implemented for finite Weyl groups" + raise NotImplementedError("reflections are only implemented for finite Weyl groups") def _repr_(self): """ @@ -470,7 +470,7 @@ def simple_reflection(self, i): [ 0 0 1] """ if i not in self.index_set(): - raise ValueError, "i must be in the index set" + raise ValueError("i must be in the index set") return self.simple_reflections()[i] def long_element_hardcoded(self): @@ -513,7 +513,7 @@ def long_element_hardcoded(self): [0, 0, 0, 0, -half, half, half, half]] m = matrix(QQ, 8, l) else: - raise NotImplementedError, "Not implemented yet for this type" + raise NotImplementedError("Not implemented yet for this type") elif type[0] == 'G': third = ZZ(1)/ZZ(3) twothirds = ZZ(2)/ZZ(3) diff --git a/src/sage/combinat/schubert_polynomial.py b/src/sage/combinat/schubert_polynomial.py index 6d184d73522..40c62074b11 100644 --- a/src/sage/combinat/schubert_polynomial.py +++ b/src/sage/combinat/schubert_polynomial.py @@ -119,7 +119,7 @@ def divided_difference(self, i): elif i in permutation.Permutations(): return symmetrica.divdiff_perm_schubert(i, self) else: - raise TypeError, "i must either be an integer or permutation" + raise TypeError("i must either be an integer or permutation") def scalar_product(self, x): """ @@ -146,7 +146,7 @@ def scalar_product(self, x): if is_SchubertPolynomial(x): return symmetrica.scalarproduct_schubert(self, x) else: - raise TypeError, "x must be a Schubert polynomial" + raise TypeError("x must be a Schubert polynomial") def multiply_variable(self, i): """ @@ -169,7 +169,7 @@ def multiply_variable(self, i): if isinstance(i, Integer): return symmetrica.mult_schubert_variable(self, i) else: - raise TypeError, "i must be an integer" + raise TypeError("i must be an integer") # FIXME: inherit from CombinatorialFreeModule once the # coercion from ground ring is implemented in the category @@ -220,12 +220,12 @@ def _element_constructor_(self, x): if isinstance(x, list): #checking the input to avoid symmetrica crashing Sage, see trac 12924 if not x in Permutations(): - raise ValueError, "The input %s is not a valid permutation"%(x) + raise ValueError("The input %s is not a valid permutation"%(x)) perm = permutation.Permutation(x).remove_extra_fixed_points() return self._from_dict({ perm: self.base_ring()(1) }) elif isinstance(x, permutation.Permutation): if not list(x) in Permutations(): - raise ValueError, "The input %s is not a valid permutation"%(x) + raise ValueError("The input %s is not a valid permutation"%(x)) perm = x.remove_extra_fixed_points() return self._from_dict({ perm: self.base_ring()(1) }) elif is_MPolynomial(x): diff --git a/src/sage/combinat/sf/classical.py b/src/sage/combinat/sf/classical.py index 67b23df0cdf..bb6a71314b3 100644 --- a/src/sage/combinat/sf/classical.py +++ b/src/sage/combinat/sf/classical.py @@ -180,7 +180,7 @@ def _element_constructor_(self, x): try: t = conversion_functions[(xP.basis_name(),self.basis_name())] except AttributeError: - raise TypeError, "do not know how to convert from %s to %s"%(xP.basis_name(), self.basis_name()) + raise TypeError("do not know how to convert from %s to %s"%(xP.basis_name(), self.basis_name())) if R == QQ and xP.base_ring() == QQ: if xm: @@ -226,7 +226,7 @@ def _element_constructor_(self, x): zero = BR.zero() PBR = P.base_ring() if not BR.has_coerce_map_from(PBR): - raise TypeError, "no coerce map from x's parent's base ring (= %s) to self's base ring (= %s)"%(PBR, self.base_ring()) + raise TypeError("no coerce map from x's parent's base ring (= %s) to self's base ring (= %s)"%(PBR, self.base_ring())) z_elt = {} for m, c in x._monomial_coefficients.iteritems(): @@ -314,7 +314,7 @@ def _element_constructor_(self, x): try: return eclass(self, {sage.combinat.partition.Partition([]):R(x)}) except Exception: - raise TypeError, "do not know how to make x (= %s) an element of self"%(x) + raise TypeError("do not know how to make x (= %s) an element of self"%(x)) # This subclass is currently needed for the test above: # isinstance(x, SymmetricFunctionAlgebra_classical.Element): diff --git a/src/sage/combinat/sf/hall_littlewood.py b/src/sage/combinat/sf/hall_littlewood.py index 553f479f349..15b021d60d2 100644 --- a/src/sage/combinat/sf/hall_littlewood.py +++ b/src/sage/combinat/sf/hall_littlewood.py @@ -91,7 +91,7 @@ def __init__(self, Sym, t = 't'): """ self._sym = Sym if not (t in Sym.base_ring() or var(t) in Sym.base_ring()): - raise ValueError, "parameter t must be in the base ring" + raise ValueError("parameter t must be in the base ring") self.t = Sym.base_ring()(t) self._name_suffix = "" if str(t) !='t': diff --git a/src/sage/combinat/sf/jack.py b/src/sage/combinat/sf/jack.py index ccbaf37aaee..efa807c0294 100644 --- a/src/sage/combinat/sf/jack.py +++ b/src/sage/combinat/sf/jack.py @@ -71,7 +71,7 @@ def __init__(self, Sym, t='t'): """ self._sym = Sym if not (t in Sym.base_ring() or var(t) in Sym.base_ring()): - raise ValueError, "parameter t must be in the base ring" + raise ValueError("parameter t must be in the base ring") self.t = Sym.base_ring()(t) self._name_suffix = "" if str(t) !='t': diff --git a/src/sage/combinat/sf/kfpoly.py b/src/sage/combinat/sf/kfpoly.py index 345b74adac5..ed99fa42703 100644 --- a/src/sage/combinat/sf/kfpoly.py +++ b/src/sage/combinat/sf/kfpoly.py @@ -56,12 +56,12 @@ def KostkaFoulkesPolynomial(mu, nu, t=None): q """ if mu not in sage.combinat.partition.Partitions_all(): - raise ValueError, "mu must be a partition" + raise ValueError("mu must be a partition") if nu not in sage.combinat.partition.Partitions_all(): - raise ValueError, "nu must be a partition" + raise ValueError("nu must be a partition") if sum(mu) != sum(nu): - raise ValueError, "mu and nu must be partitions of the same size" + raise ValueError("mu and nu must be partitions of the same size") return kfpoly(mu, nu, t) diff --git a/src/sage/combinat/sf/llt.py b/src/sage/combinat/sf/llt.py index bf95c71e951..700a94aff35 100644 --- a/src/sage/combinat/sf/llt.py +++ b/src/sage/combinat/sf/llt.py @@ -122,7 +122,7 @@ def __init__(self, Sym, k, t='t'): self._sym = Sym self._name = "level %s LLT polynomials"%self._k if not (t in Sym.base_ring() or var(t) in Sym.base_ring()): - raise ValueError, "parameter t must be in the base ring" + raise ValueError("parameter t must be in the base ring") self.t = Sym.base_ring()(t) self._name_suffix = "" if str(t) !='t': @@ -245,7 +245,7 @@ def _llt_generic(self, skp, stat): if skp in sage.combinat.partition.Partitions(): m = (sum(skp) / self.level()).floor() if m == 0: - raise ValueError, "level (%=) must divide %s "%(sum(skp), self.level()) + raise ValueError("level (%=) must divide %s "%(sum(skp), self.level())) mu = sage.combinat.partition.Partitions( ZZ(sum(skp) / self.level()) ) elif isinstance(skp, list) and skp[0] in sage.combinat.skew_partition.SkewPartitions(): @@ -259,7 +259,7 @@ def _llt_generic(self, skp, stat): skp = sage.combinat.partition.Partition(core=[], quotient=skp) mu = sage.combinat.partition.Partitions( ZZ(sum(skp) / self.level() )) else: - raise ValueError, "LLT polynomials not defined for %s"%skp + raise ValueError("LLT polynomials not defined for %s"%skp) BR = self.base_ring() return sum([ BR(stat(skp,nu,self.level()).subs(t=self.t))*self._m(nu) for nu in mu]) diff --git a/src/sage/combinat/sf/macdonald.py b/src/sage/combinat/sf/macdonald.py index f45a02b085d..0c7bda5ef2f 100644 --- a/src/sage/combinat/sf/macdonald.py +++ b/src/sage/combinat/sf/macdonald.py @@ -121,10 +121,10 @@ def __init__(self, Sym, q='q', t='t'): self._sym = Sym self._s = Sym.s() if not (q in Sym.base_ring() or var(q) in Sym.base_ring()): - raise ValueError, "parameter q must be in the base ring" + raise ValueError("parameter q must be in the base ring") self.q = Sym.base_ring()(q) if not (t in Sym.base_ring() or var(t) in Sym.base_ring()): - raise ValueError, "parameter t must be in the base ring" + raise ValueError("parameter t must be in the base ring") self.t = Sym.base_ring()(t) self._name_suffix = "" if str(q) !='q': @@ -1476,7 +1476,7 @@ def _creation_by_determinant_helper(self, k, part): part += [0]*(k-len(part)) if len(part) > k: - raise ValueError, "the column to add is too small" + raise ValueError("the column to add is too small") #Create the matrix over the homogeneous symmetric #functions and take its determinant diff --git a/src/sage/combinat/sf/monomial.py b/src/sage/combinat/sf/monomial.py index cf73a5a371a..fa2fa6af11f 100644 --- a/src/sage/combinat/sf/monomial.py +++ b/src/sage/combinat/sf/monomial.py @@ -174,7 +174,7 @@ def from_polynomial(self, f, check=True): for (e,c) in f.dict().iteritems() if tuple(sorted(e)) == tuple(reversed(e))) if check and out.expand(f.parent().ngens(),f.parent().gens()) != f: - raise ValueError, "%s is not a symmetric polynomial"%f + raise ValueError("%s is not a symmetric polynomial"%f) return out def from_polynomial_exp(self, p): diff --git a/src/sage/combinat/sf/new_kschur.py b/src/sage/combinat/sf/new_kschur.py index ebe979b7a4a..44c10c37bee 100644 --- a/src/sage/combinat/sf/new_kschur.py +++ b/src/sage/combinat/sf/new_kschur.py @@ -86,10 +86,10 @@ def __init__(self, Sym, k, t='t'): sage: TestSuite(Sym.kBoundedSubspace(1)).run(skip=["_test_not_implemented_methods"]) """ if not isinstance(k, (int, Integer)) or (k < 1): - raise ValueError, "k must be a positive integer" + raise ValueError("k must be a positive integer") if not isinstance(Sym,SymmetricFunctions): - raise ValueError, "Sym must be an algebra of symmetric functions" + raise ValueError("Sym must be an algebra of symmetric functions") self.indices = ConstantFunction(Partitions_all_bounded(k)) @@ -198,7 +198,7 @@ def khomogeneous(self): sage: TestSuite(kh3).run() """ if self.t!=1: - raise ValueError, "This basis only exists for t=1" + raise ValueError("This basis only exists for t=1") return kHomogeneous(self) def K_kschur(self): @@ -228,7 +228,7 @@ def K_kschur(self): ValueError: This basis only exists for t=1 """ if self.t!=1: - raise ValueError, "This basis only exists for t=1" + raise ValueError("This basis only exists for t=1") return K_kSchur(self) @@ -1508,7 +1508,7 @@ def _g_to_kh_on_basis(self,la): ValueError: Partition should be 3-bounded """ if la != [] and (la[0] > self.k): - raise ValueError, "Partition should be %d-bounded"%self.k + raise ValueError("Partition should be %d-bounded"%self.k) return self._DualGrothendieck(Partition(la)) def K_k_Schur_non_commutative_variables(self,la): diff --git a/src/sage/combinat/sf/ns_macdonald.py b/src/sage/combinat/sf/ns_macdonald.py index 7de1ceb1d97..a2b544a8e71 100644 --- a/src/sage/combinat/sf/ns_macdonald.py +++ b/src/sage/combinat/sf/ns_macdonald.py @@ -45,7 +45,7 @@ def __getitem__(self, i): 2 """ if i == 0: - raise ValueError, "indexing starts at 1" + raise ValueError("indexing starts at 1") elif i < 0: i += 1 return self._list[i-1] @@ -221,7 +221,7 @@ def __getitem__(self, i): 4 """ if i < 1: - raise ValueError, "indexing starts at 1" + raise ValueError("indexing starts at 1") if isinstance(i, tuple): i,j = i return self._list[i-1][j] @@ -769,7 +769,7 @@ def get_next_pos(self, ii, jj): if self._shape[i] >= jj + 1: return i, jj + 1 - raise ValueError, "we should never be here" + raise ValueError("we should never be here") def _check_muqt(mu, q, t, pi=None): @@ -811,10 +811,10 @@ def _check_muqt(mu, q, t, pi=None): q,t = P.gens() elif q is not None and t is not None: if q.parent() != t.parent(): - raise ValueError, "the parents of q and t must be the same" + raise ValueError("the parents of q and t must be the same") P = q.parent() else: - raise ValueError, "you must specify either both q and t or neither of them" + raise ValueError("you must specify either both q and t or neither of them") n = NonattackingFillings(mu, pi) R = PolynomialRing(P, len(n._shape), 'x') x = R.gens() diff --git a/src/sage/combinat/skew_tableau.py b/src/sage/combinat/skew_tableau.py index 182c8a40106..c9e59e6519f 100644 --- a/src/sage/combinat/skew_tableau.py +++ b/src/sage/combinat/skew_tableau.py @@ -707,7 +707,7 @@ def slide(self, corner=None): outer_corners = self.outer_shape().corners() if corner is not None: if tuple(corner) not in inner_corners: - raise ValueError, "corner must be an inner corner" + raise ValueError("corner must be an inner corner") else: if len(inner_corners) == 0: return self diff --git a/src/sage/combinat/sloane_functions.py b/src/sage/combinat/sloane_functions.py index dd44375078c..cadfcb8090f 100644 --- a/src/sage/combinat/sloane_functions.py +++ b/src/sage/combinat/sloane_functions.py @@ -214,13 +214,13 @@ def __call__(self, n): ValueError: input n (=0) must be a positive integer """ if not isinstance(n, (int, long, Integer_class)): - raise TypeError, "input must be an int, long, or Integer" + raise TypeError("input must be an int, long, or Integer") m = ZZ(n) if m < self.offset: if self.offset == 1: - raise ValueError, "input n (=%s) must be a positive integer" % (n) + raise ValueError("input n (=%s) must be a positive integer" % (n)) else: - raise ValueError, "input n (=%s) must be an integer >= %s" % (n, self.offset) + raise ValueError("input n (=%s) must be an integer >= %s" % (n, self.offset)) return self._eval(m) def _eval(self, n): @@ -291,7 +291,7 @@ def __getitem__(self, n): LENGTH = 100000 (start, stop, step) = n.indices(2*LENGTH) if abs(stop - start) > LENGTH: - raise IndexError, "slice (=%s) too long"%n + raise IndexError("slice (=%s) too long"%n) # The dirty work of generating indices is left to a range list # This could be slow but in practice seems fine # NOTE: n is a SLICE, not an index @@ -9738,6 +9738,6 @@ def __getattribute__(self, name): setattr(self, name, seq) return seq except AttributeError: - raise AttributeError, name + raise AttributeError(name) sloane = Sloane() diff --git a/src/sage/combinat/species/misc.py b/src/sage/combinat/species/misc.py index f3bfd007e68..805f2316500 100644 --- a/src/sage/combinat/species/misc.py +++ b/src/sage/combinat/species/misc.py @@ -63,7 +63,7 @@ def accept_size(f): def new_func(*args, **kwds): if 'size' in kwds: if 'min' in kwds or 'max' in kwds: - raise ValueError, "cannot specify both size and (min or max)" + raise ValueError("cannot specify both size and (min or max)") kwds['min'] = kwds['size'] kwds['max'] = kwds['size'] + 1 del kwds['size'] diff --git a/src/sage/combinat/species/recursive_species.py b/src/sage/combinat/species/recursive_species.py index f6f3cfce823..264c538bec3 100644 --- a/src/sage/combinat/species/recursive_species.py +++ b/src/sage/combinat/species/recursive_species.py @@ -382,10 +382,10 @@ def define(self, x): [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] """ if not isinstance(x, GenericCombinatorialSpecies): - raise TypeError, "x must be a combinatorial species" + raise TypeError("x must be a combinatorial species") if self.__class__ is not CombinatorialSpecies: - raise TypeError, "only undefined combinatorial species can be set" + raise TypeError("only undefined combinatorial species can be set") self._reference = x diff --git a/src/sage/combinat/species/series.py b/src/sage/combinat/species/series.py index 70f9f9c8d21..b888194793c 100644 --- a/src/sage/combinat/species/series.py +++ b/src/sage/combinat/species/series.py @@ -52,11 +52,11 @@ def __init__(self, R, element_class = None, names=None): """ #Make sure R is a ring with unit element if not R in Rings(): - raise TypeError, "Argument R must be a ring." + raise TypeError("Argument R must be a ring.") try: z = R(Integer(1)) except Exception: - raise ValueError, "R must have a unit element" + raise ValueError("R must have a unit element") #Take care of the names if names is None: @@ -201,7 +201,7 @@ def __call__(self, x=None, order=unk): x = BR(x) return self.term(x, 0) - raise TypeError, "do not know how to coerce %s into self"%x + raise TypeError("do not know how to coerce %s into self"%x) def zero_element(self): """ @@ -250,7 +250,7 @@ def term(self, r, n): [0, 0, 3, 0, 0] """ if n < 0: - raise ValueError, "n must be non-negative" + raise ValueError("n must be non-negative") BR = self.base_ring() if r == 0: res = self._new_initial(inf, Stream([0])) @@ -1160,7 +1160,7 @@ def __pow__(self, n): 1 """ if not isinstance(n, (int, Integer)) or n < 0: - raise ValueError, "n must be a nonnegative integer" + raise ValueError("n must be a nonnegative integer") return prod([self]*n, self.parent().identity_element()) def __call__(self, y): @@ -1688,4 +1688,4 @@ def uninitialized(): ... RuntimeError: we should never be here """ - raise RuntimeError, "we should never be here" + raise RuntimeError("we should never be here") diff --git a/src/sage/combinat/species/series_order.py b/src/sage/combinat/species/series_order.py index 222d383fe52..17fa96201c4 100644 --- a/src/sage/combinat/species/series_order.py +++ b/src/sage/combinat/species/series_order.py @@ -53,7 +53,7 @@ def __add__(self, x): """ if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") return self if isinstance(x, InfiniteSeriesOrder): @@ -62,7 +62,7 @@ def __add__(self, x): if isinstance(x, UnknownSeriesOrder): return x - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") __radd__ = __add__ @@ -93,7 +93,7 @@ def __mul__(self, x): """ if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") elif x == 0: return x return self @@ -104,7 +104,7 @@ def __mul__(self, x): if isinstance(x, UnknownSeriesOrder): return x - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") __rmul__ = __mul__ @@ -129,7 +129,7 @@ def __lt__(self, x): """ if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") return False if isinstance(x, InfiniteSeriesOrder): @@ -139,7 +139,7 @@ def __lt__(self, x): return False - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") def __gt__(self, x): @@ -178,13 +178,13 @@ def __add__(self, x): if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") return self if isinstance(x, SeriesOrderElement): return self - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") __radd__ = __add__ @@ -202,13 +202,13 @@ def __mul__(self, x): """ if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") return self if isinstance(x, SeriesOrderElement): return self - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") __rmul__ = __mul__ @@ -226,13 +226,13 @@ def __lt__(self, x): """ if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") return True if isinstance(x, SeriesOrderElement): return True - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") def __gt__(self, x): """ @@ -263,10 +263,10 @@ def bounded_decrement(x): if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") return max(0, x - 1) - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") def increment(x): @@ -285,10 +285,10 @@ def increment(x): if isinstance(x, (int, Integer)): if x < 0: - raise ValueError, "x must be a positive integer" + raise ValueError("x must be a positive integer") return x+1 - raise TypeError, "x must be a positive integer or a SeriesOrderElement" + raise TypeError("x must be a positive integer or a SeriesOrderElement") inf = InfiniteSeriesOrder() unk = UnknownSeriesOrder() diff --git a/src/sage/combinat/species/species.py b/src/sage/combinat/species/species.py index 455804c3dd2..d605329ce12 100644 --- a/src/sage/combinat/species/species.py +++ b/src/sage/combinat/species/species.py @@ -260,7 +260,7 @@ def __add__(self, g): """ from sum_species import SumSpecies if not isinstance(g, GenericCombinatorialSpecies): - raise TypeError, "g must be a combinatorial species" + raise TypeError("g must be a combinatorial species") return SumSpecies(self, g) sum = __add__ @@ -277,7 +277,7 @@ def __mul__(self, g): """ from product_species import ProductSpecies if not isinstance(g, GenericCombinatorialSpecies): - raise TypeError, "g must be a combinatorial species" + raise TypeError("g must be a combinatorial species") return ProductSpecies(self, g) product = __mul__ @@ -292,7 +292,7 @@ def __call__(self, g): """ from composition_species import CompositionSpecies if not isinstance(g, GenericCombinatorialSpecies): - raise TypeError, "g must be a combinatorial species" + raise TypeError("g must be a combinatorial species") return CompositionSpecies(self, g) composition = __call__ @@ -313,7 +313,7 @@ def functorial_composition(self, g): """ from functorial_composition_species import FunctorialCompositionSpecies if not isinstance(g, GenericCombinatorialSpecies): - raise TypeError, "g must be a combinatorial species" + raise TypeError("g must be a combinatorial species") return FunctorialCompositionSpecies(self, g) @@ -413,7 +413,7 @@ def __pow__(self, n): import operator n = Integer(n) if n <= 0: - raise ValueError, "only positive exponents are currently supported" + raise ValueError("only positive exponents are currently supported") digits = n.digits(2) squares = [self] for i in range(len(digits)-1): @@ -486,9 +486,9 @@ def _series_helper(self, series_ring_class, prefix, base_ring=None): #The specified base ring must have maps from both #the rational numbers and the weight ring if not base_ring.has_coerce_map_from(QQ): - raise ValueError, "specified base ring does not contain the rationals" + raise ValueError("specified base ring does not contain the rationals") if not base_ring.has_coerce_map_from(self.weight_ring()): - raise ValueError, "specified base ring is incompatible with the weight ring of self" + raise ValueError("specified base ring is incompatible with the weight ring of self") series_ring = series_ring_class(base_ring) @@ -646,7 +646,7 @@ def _common_parent(self, parents): for p in parents[1:]: common = cm.explain(common, p, verbosity=0) if common is None: - raise ValueError, "unable to find a common parent" + raise ValueError("unable to find a common parent") return common def digraph(self): diff --git a/src/sage/combinat/species/stream.py b/src/sage/combinat/species/stream.py index 28ea0aa3927..0a33b98c4e2 100644 --- a/src/sage/combinat/species/stream.py +++ b/src/sage/combinat/species/stream.py @@ -158,7 +158,7 @@ def __init__(self, gen=None, const=None, func=None): if func is not None: if gen is not None: - raise ValueError, "you cannot specify both a function and a generator" + raise ValueError("you cannot specify both a function and a generator") gen = _apply_function(func, self._list) #Constant stream @@ -326,7 +326,7 @@ def __getitem__(self, i): if self._constant is not False: return self._constant else: - raise IndexError, "out of position" + raise IndexError("out of position") else: while self._last_index < i: try: diff --git a/src/sage/combinat/subset.py b/src/sage/combinat/subset.py index c7446e80493..00661c0e5f7 100644 --- a/src/sage/combinat/subset.py +++ b/src/sage/combinat/subset.py @@ -100,7 +100,7 @@ def Subsets(s, k=None, submultiset=False): if isinstance(s, (int, Integer)): if s < 0: - raise ValueError, "s must be non-negative" + raise ValueError("s must be non-negative") s = Set(range(1,s+1)) # if len(Set(s)) != len(s): diff --git a/src/sage/combinat/subword.py b/src/sage/combinat/subword.py index f41aa503638..6221225c96a 100644 --- a/src/sage/combinat/subword.py +++ b/src/sage/combinat/subword.py @@ -83,7 +83,7 @@ def Subwords(w, k=None): return Subwords_w(w) else: if k not in range(0, len(w)+1): - raise ValueError, "k must be between 0 and %s"%len(w) + raise ValueError("k must be between 0 and %s"%len(w)) else: return Subwords_wk(w,k) diff --git a/src/sage/combinat/symmetric_group_representations.py b/src/sage/combinat/symmetric_group_representations.py index 7da84b9cade..c77bf7d0179 100644 --- a/src/sage/combinat/symmetric_group_representations.py +++ b/src/sage/combinat/symmetric_group_representations.py @@ -174,7 +174,7 @@ def SymmetricGroupRepresentation(partition, implementation="specht", return SpechtRepresentation(partition, ring=ring, cache_matrices=cache_matrices) else: - raise NotImplementedError, "only seminormal, orthogonal and specht are implemented" + raise NotImplementedError("only seminormal, orthogonal and specht are implemented") def SymmetricGroupRepresentations(n, implementation="specht", ring=None, cache_matrices=True): @@ -248,7 +248,7 @@ def SymmetricGroupRepresentations(n, implementation="specht", ring=None, elif implementation == "specht": return SpechtRepresentations(n, ring=ring) else: - raise NotImplementedError, "only seminormal, orthogonal and specht are implemented" + raise NotImplementedError("only seminormal, orthogonal and specht are implemented") ##### Generic classes for symmetric group representations ################# @@ -476,7 +476,7 @@ def __call__(self, partition): Seminormal representation of the symmetric group corresponding to [2, 1] """ if Partition(partition).size() != self._n: - raise TypeError, "not a partition of %s" % self._n + raise TypeError("not a partition of %s" % self._n) return self.object_class(partition, ring=self._ring, cache_matrices=self._cache_matrices) diff --git a/src/sage/combinat/tableau.py b/src/sage/combinat/tableau.py index 36980e00cef..5f13bb3f58b 100644 --- a/src/sage/combinat/tableau.py +++ b/src/sage/combinat/tableau.py @@ -611,7 +611,7 @@ def __call__(self, *cell): try: return self[i][j] except IndexError: - raise IndexError, "The cell (%d,%d) is not contained in %s"%(i,j,self) + raise IndexError("The cell (%d,%d) is not contained in %s"%(i,j,self)) def level(self): """ @@ -1967,7 +1967,7 @@ def bump_multiply(left, right): [[1, 1, 2, 2, 3], [2, 2, 3, 5], [3, 4, 5], [4, 6, 6], [5]] """ if not isinstance(right, Tableau): - raise TypeError, "right must be a Tableau" + raise TypeError("right must be a Tableau") row = len(right) product = copy.deepcopy(left) @@ -2543,7 +2543,7 @@ def add_entry(self,cell,m): tab[r].append(m) else: - raise IndexError, '%s is not an addable cell of the tableau' % ((r,c),) + raise IndexError('%s is not an addable cell of the tableau' % ((r,c),)) # attempt to return a tableau of the same type as self if tab in self.parent(): diff --git a/src/sage/combinat/tableau_tuple.py b/src/sage/combinat/tableau_tuple.py index 5ddf2aa9994..091fa59498d 100644 --- a/src/sage/combinat/tableau_tuple.py +++ b/src/sage/combinat/tableau_tuple.py @@ -635,7 +635,7 @@ def __call__(self, *cell): try: return self[k][r][c] except IndexError: - raise IndexError, "The cell (%s, %s, %s) is not contained in the tableau"% (k,r,c) + raise IndexError("The cell (%s, %s, %s) is not contained in the tableau"% (k,r,c)) def level(self): """ @@ -1063,7 +1063,7 @@ def add_entry(self,cell,m): tab[k][r].append(m) else: - raise IndexError, '%s is not an addable cell of the tableau' % ( (k,r,c),) + raise IndexError('%s is not an addable cell of the tableau' % ( (k,r,c),)) # finally, try and return a tableau belonging to the same category try: @@ -1851,7 +1851,7 @@ def list(self): if self.is_finite(): return [y for y in self] else: - raise NotImplementedError, 'this is an infinite set of tableaux' + raise NotImplementedError('this is an infinite set of tableaux') class TableauTuples_all(TableauTuples): @@ -2312,14 +2312,14 @@ def __classcall_private__(cls, *args, **kwargs): else: size=args[1] elif len(args)>2: - raise ValueError,'too man arguments!' + raise ValueError('too man arguments!') # now check that the arguments are consistent if level is not None and (not isinstance(level, (int,Integer)) or level<1): - raise ValueError,'the level must be a positive integer' + raise ValueError('the level must be a positive integer') if size is not None and (not isinstance(size, (int,Integer)) or size<0): - raise ValueError,'the size must be a non-negative integer' + raise ValueError('the size must be a non-negative integer') if shape is not None: try: @@ -2330,11 +2330,11 @@ def __classcall_private__(cls, *args, **kwargs): if level is None: level=shape.level() elif level!=shape.level(): - raise ValueError,'the shape and level must agree' + raise ValueError('the shape and level must agree') if size is None: size=shape.size() elif size!=shape.size(): - raise ValueError,'the shape and size must agree' + raise ValueError('the shape and size must agree') # now that the inputs appear to make sense, return the appropriate class if level is not None and level<=1: diff --git a/src/sage/combinat/words/abstract_word.py b/src/sage/combinat/words/abstract_word.py index c038ede92f3..b9aca87ed58 100644 --- a/src/sage/combinat/words/abstract_word.py +++ b/src/sage/combinat/words/abstract_word.py @@ -149,7 +149,7 @@ def __iter__(self): ... NotImplementedError: you need to define an iterator in __iter__ """ - raise NotImplementedError, "you need to define an iterator in __iter__" + raise NotImplementedError("you need to define an iterator in __iter__") def length(self): r""" @@ -249,7 +249,7 @@ def __len__(self): if L is None or L is Infinity: msg = "Python len method can not return a non integer value (=%s): "%L msg += "use length method instead." - raise TypeError, msg + raise TypeError(msg) return int(L) def __cmp__(self, other): @@ -1154,7 +1154,7 @@ def iterated_right_palindromic_closure(self, f=None, algorithm='recursive'): elif algorithm == 'recursive': it = self._iterated_right_palindromic_closure_recursive_iterator(f=f) else: - raise ValueError, "algorithm (=%s) must be either 'definition' or 'recursive'" + raise ValueError("algorithm (=%s) must be either 'definition' or 'recursive'") return self._parent(it, length=length) def prefixes_iterator(self, max_length=None): @@ -1291,7 +1291,7 @@ def _partial_sums_iterator(self, start, mod=None): sum = Zn(start) else: - raise TypeError, 'mod(=%s) must be None or an integer'%mod + raise TypeError('mod(=%s) must be None or an integer'%mod) yield sum for letter in self: @@ -1425,7 +1425,7 @@ def _finite_differences_iterator(self, mod=None): yield Zn(j.next() - i.next()) else: - raise TypeError, 'mod(=%s) must be None or an integer'%mod + raise TypeError('mod(=%s) must be None or an integer'%mod) def finite_differences(self, mod=None): r""" @@ -1571,7 +1571,7 @@ def sum_digits(self, base=2, mod=None): elif mod in ZZ and mod >= 2: alphabet = range(mod) else: - raise ValueError, "base (=%s) and mod (=%s) must be integers greater or equal to 2"%(base, mod) + raise ValueError("base (=%s) and mod (=%s) must be integers greater or equal to 2"%(base, mod)) # The iterator f = partial(words._ThueMorseWord_nth_digit, alphabet=alphabet, base=base) @@ -1613,9 +1613,9 @@ def factor_occurrences_iterator(self, fact): 24 """ if fact.is_empty(): - raise NotImplementedError, "The factor must be non empty" + raise NotImplementedError("The factor must be non empty") if not fact.is_finite(): - raise ValueError, "The factor must be finite" + raise ValueError("The factor must be finite") p = fact._pos_in(self, 0) while p is not None: yield p diff --git a/src/sage/combinat/words/finite_word.py b/src/sage/combinat/words/finite_word.py index 71393ebfc1d..cdb65738f2a 100644 --- a/src/sage/combinat/words/finite_word.py +++ b/src/sage/combinat/words/finite_word.py @@ -301,7 +301,7 @@ def coerce(self, other): self = other.parent()(self) self.parent()._check(self, length=None) except Exception: - raise TypeError, "no coercion rule between %r and %r" % (self.parent(), other.parent()) + raise TypeError("no coercion rule between %r and %r" % (self.parent(), other.parent())) return self, other def __hash__(self): @@ -466,9 +466,9 @@ def __pow__(self, exp): if length in ZZ and length >= 0: return self._parent(fcn, length=length) else: - raise ValueError, "Power of the word is not defined on the \ + raise ValueError("Power of the word is not defined on the \ exponent %s: the length of the word (%s) times the exponent \ -(%s) must be a positive integer" % (exp, self.length(), exp) +(%s) must be a positive integer" % (exp, self.length(), exp)) def length(self): r""" @@ -1955,7 +1955,7 @@ def longest_common_suffix(self, other): TypeError: other must be a finite word """ if not isinstance(other, FiniteWord_class): - raise TypeError, "other must be a finite word" + raise TypeError("other must be a finite word") if self.is_empty(): return self @@ -2094,7 +2094,7 @@ def is_palindrome(self, f=None): if not isinstance(f, WordMorphism): f = WordMorphism(f) if not f.is_involution(): - raise ValueError, "f must be an involution" + raise ValueError("f must be an involution") return self[:l/2 + l%2] == f(self[l/2:].reversal()) def lps(self, f=None, l=None): @@ -2608,7 +2608,7 @@ def defect(self, f=None): if not isinstance(f, WordMorphism): f = WordMorphism(f) if not f.is_involution(): - raise ValueError, "f must be an involution" + raise ValueError("f must be an involution") D = f.domain() A = set(map(D,set(self))) while A: @@ -3476,7 +3476,7 @@ def degree(self, weights=None): if all(x in ZZ for x in self): return sum(self) - raise TypeError, "degree is not defined for your word" + raise TypeError("degree is not defined for your word") def deg_lex_less(self, other, weights=None): r""" @@ -3798,7 +3798,7 @@ def factor_occurrences_in(self, other): [0, 2, 8] """ if self.length() == 0: - raise NotImplementedError, "The factor must be non empty" + raise NotImplementedError("The factor must be non empty") p = self._pos_in(other, 0) while p is not None: yield p @@ -3844,7 +3844,7 @@ def nb_subword_occurrences_in(self, other): """ ls = self.length() if ls == 0: - raise NotImplementedError, "undefined value" + raise NotImplementedError("undefined value") elif ls == 1: return self.nb_factor_occurrences_in(other) elif len(other) < ls: @@ -4350,18 +4350,18 @@ def overlap_partition(self, other, delay=0, p=None, involution=None) : 109 pages. """ if not isinstance(delay, (int, Integer)): - raise TypeError, "delay (=%s) must be an integer"%delay + raise TypeError("delay (=%s) must be an integer"%delay) elif delay < 0: return other.overlap_partition(self, -delay, p) from sage.sets.disjoint_set import DisjointSet_class if p is None: if self.parent().size_of_alphabet() is Infinity: - raise ValueError, "The alphabet of the parent must be finite" + raise ValueError("The alphabet of the parent must be finite") from sage.sets.disjoint_set import DisjointSet p = DisjointSet(self.parent().alphabet()) elif not isinstance(p, DisjointSet_class): - raise TypeError, "p(=%s) is not a DisjointSet" % p + raise TypeError("p(=%s) is not a DisjointSet" % p) #Join the classes of each pair of letters that are one above the other from itertools import islice, izip @@ -4380,7 +4380,7 @@ def overlap_partition(self, other, delay=0, p=None, involution=None) : p.union(a, b) p.union(involution(a), involution(b)) else: - raise TypeError, "involution (=%s) must be callable"%involution + raise TypeError("involution (=%s) must be callable"%involution) return p # TODO: requires a parent with a cmp_letters method @@ -4906,7 +4906,7 @@ def is_balanced(self, q=1): University Press, U.K., 2002. """ if not isinstance(q, (int, Integer)) or q <= 0: - raise TypeError, "the balance level must be a positive integer" + raise TypeError("the balance level must be a positive integer") alphabet = set(self) for i in xrange(2, self.length()): empty_sets = [set() for _ in range(len(alphabet))] @@ -5337,7 +5337,7 @@ def parikh_vector(self, alphabet=None): TypeError: the alphabet is infinite; specify a finite alphabet or use evaluation_dict() instead """ if alphabet is None and self._parent.size_of_alphabet() is Infinity: - raise TypeError, "the alphabet is infinite; specify a finite alphabet or use evaluation_dict() instead" + raise TypeError("the alphabet is infinite; specify a finite alphabet or use evaluation_dict() instead") if alphabet is None: alphabet = self._parent._alphabet ev_dict = self.evaluation_dict() @@ -5430,14 +5430,14 @@ def shuffle(self, other, overlap=0): return ShuffleProduct_w1w2(self, other) else: if any(a not in ZZ for a in self) or any(a not in ZZ for a in other): - raise ValueError, "for a nonzero overlap, words must contain integers as letters" + raise ValueError("for a nonzero overlap, words must contain integers as letters") if overlap is True: from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping return ShuffleProduct_overlapping(self, other) elif isinstance(overlap, (int,Integer)): from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping_r return ShuffleProduct_overlapping_r(self, other, overlap) - raise ValueError, 'overlapping must be True or an integer' + raise ValueError('overlapping must be True or an integer') def shifted_shuffle(self, other, shift=None): r""" @@ -5477,7 +5477,7 @@ def shifted_shuffle(self, other, shift=None): ValueError: for shifted shuffle, words must only contain integers as letters """ if any(a not in ZZ for a in self) or any(a not in ZZ for a in other): - raise ValueError, "for shifted shuffle, words must only contain integers as letters" + raise ValueError("for shifted shuffle, words must only contain integers as letters") if shift is None: from sage.combinat.words.shuffle_product import ShuffleProduct_shifted return ShuffleProduct_shifted(self, other) @@ -5514,7 +5514,7 @@ def delta_inv(self, W=None, s=None): s = cycle_alphabet.next() else: if s not in alphabet: - raise ValueError, "starting letter not in alphabet" + raise ValueError("starting letter not in alphabet") t = cycle_alphabet.next() while t != s: t = cycle_alphabet.next() @@ -6022,7 +6022,7 @@ def colored_vector(self, x=0, y=0, width='default', height=1, cmap='hsv', thickn isinstance(cm.__dict__[x], C)]) import sage.misc.misc sage.misc.misc.verbose("The possible color maps include: %s"%possibilities, level=0) - raise RuntimeError, "Color map %s not known"%cmap + raise RuntimeError("Color map %s not known"%cmap) #Drawing the colored vector... from sage.plot.plot import polygon,line,text @@ -6254,7 +6254,7 @@ def __call__(self, i): if (j - c.length() < 0): return c[j] j -= c.length() - raise IndexError, "index (=%s) out of range" % i + raise IndexError("index (=%s) out of range" % i) class Factorization(list): r""" diff --git a/src/sage/combinat/words/morphism.py b/src/sage/combinat/words/morphism.py index 4e1756ee30f..2f5dda74603 100644 --- a/src/sage/combinat/words/morphism.py +++ b/src/sage/combinat/words/morphism.py @@ -148,7 +148,7 @@ def get_cycles(f, domain=None): try: domain = f.domain() except AttributeError: - raise ValueError, "you should specify the domain of the function f" + raise ValueError("you should specify the domain of the function f") cycles = [] not_seen = dict((letter,True) for letter in domain) for a in not_seen: @@ -319,7 +319,7 @@ def __init__(self, data, codomain=None): codomain = self._build_codomain(data) if not isinstance(codomain,Words_all): - raise TypeError, "the codomain must be a Words domain" + raise TypeError("the codomain must be a Words domain") self._codomain = codomain self._morph = {} @@ -360,13 +360,13 @@ def _build_dict(self, s): continue if len(fleche) < 3 or fleche[1:3] != '->': - raise ValueError, "The second and third characters must be '->' (not '%s')"%fleche[1:3] + raise ValueError("The second and third characters must be '->' (not '%s')"%fleche[1:3]) lettre = fleche[0] image = fleche[3:] if lettre in tmp_dict: - raise ValueError, "The image of %r is defined twice." %lettre + raise ValueError("The image of %r is defined twice." %lettre) tmp_dict[lettre] = image return tmp_dict @@ -700,7 +700,7 @@ def __call__(self, w, order=1, datatype='iter'): elif w in self._domain.alphabet(): return self._morph[w] else: - raise TypeError, "Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w + raise TypeError("Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w) return self.codomain()((x for y in w for x in self._morph[y]), length=length, datatype=datatype) elif order is Infinity: if isinstance(w, (tuple,str,list,FiniteWord_class)): @@ -716,14 +716,14 @@ def __call__(self, w, order=1, datatype='iter'): elif w in self._domain.alphabet(): letter = w else: - raise TypeError, "Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w + raise TypeError("Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w) return self.fixed_point(letter=letter) elif isinstance(order, (int,Integer)) and order > 1: return self(self(w, order-1),datatype=datatype) elif order == 0: return self._domain(w) else: - raise TypeError, "order (%s) must be a positive integer or plus Infinity" % order + raise TypeError("order (%s) must be a positive integer or plus Infinity" % order) def latex_layout(self, layout=None): r""" @@ -806,7 +806,7 @@ def _latex_(self): s += '\n' + "\end{array}" return LatexExpr(s) else: - raise ValueError, 'unknown latex_layout(=%s)' % latex_layout + raise ValueError('unknown latex_layout(=%s)' % latex_layout) def __mul__(self, other): r""" @@ -903,11 +903,11 @@ def __pow__(self, exp): """ #If exp is not an integer if not isinstance(exp, (int,Integer)): - raise ValueError, "exponent (%s) must be an integer" %exp + raise ValueError("exponent (%s) must be an integer" %exp) #If exp is negative elif exp <= 0: - raise ValueError, "exponent (%s) must be strictly positive" %exp + raise ValueError("exponent (%s) must be strictly positive" %exp) #Base of induction elif exp == 1: @@ -964,7 +964,7 @@ def extend_by(self, other): TypeError: other (=4) is not a WordMorphism """ if not isinstance(other, WordMorphism): - raise TypeError, "other (=%s) is not a WordMorphism"%other + raise TypeError("other (=%s) is not a WordMorphism"%other) nv = dict(other._morph) for k,v in self._morph.iteritems(): @@ -1315,7 +1315,7 @@ def partition_of_domain_alphabet(self): TypeError: self (=a->b, b->a, c->a) is not an endomorphism """ if not self.is_involution(): - raise TypeError, "self is not an involution" + raise TypeError("self is not an involution") A = set(); B = set(); C = set() for a in self.domain().alphabet(): @@ -1355,7 +1355,7 @@ def is_involution(self): TypeError: self (=0->1, 1->0, 2->3) is not an endomorphism """ if not self.is_endomorphism(): - raise TypeError, "self (=%s) is not an endomorphism"%self + raise TypeError("self (=%s) is not an endomorphism"%self) return (self*self).is_identity() @@ -1443,7 +1443,7 @@ def _check_primitive(self): """ if not isinstance(self.codomain(),Words_all): - raise TypeError, "codomain of self(=%s) must be an instance of Words"%self + raise TypeError("codomain of self(=%s) must be an instance of Words"%self) dom_alphabet = set(self.domain().alphabet()) @@ -1520,7 +1520,7 @@ def is_primitive(self): 2003. """ if not self.is_endomorphism(): - raise TypeError, "self (=%s) is not an endomorphism"%self + raise TypeError("self (=%s) is not an endomorphism"%self) m = self.incidence_matrix() power = m order = 1 @@ -1593,11 +1593,11 @@ def is_prolongable(self, letter): TypeError: codomain of self must be an instance of Words """ if not isinstance(self.codomain(), Words_all): - raise TypeError, "codomain of self must be an instance of Words" + raise TypeError("codomain of self must be an instance of Words") if letter not in self.domain().alphabet(): - raise TypeError, "letter (=%s) is not in the domain alphabet (=%s)"\ - %(letter, self.domain().alphabet()) + raise TypeError("letter (=%s) is not in the domain alphabet (=%s)"\ + %(letter, self.domain().alphabet())) image = self.image(letter) return not image.is_empty() and letter == image[0] @@ -1778,10 +1778,10 @@ def fixed_point(self, letter): TypeError: self (=a->aa, b->aac) is not an endomorphism """ if not self.is_endomorphism(): - raise TypeError, "self (=%s) is not an endomorphism"%self + raise TypeError("self (=%s) is not an endomorphism"%self) if not self.is_prolongable(letter=letter): - raise TypeError, "self must be prolongable on %s"%letter + raise TypeError("self must be prolongable on %s"%letter) image = self.image(letter) @@ -1851,7 +1851,7 @@ def periodic_point(self, letter): TypeError: self must be prolongable on a """ if self.is_erasing(): - raise NotImplementedError, "self should be non erasing" + raise NotImplementedError("self should be non erasing") cycle = [letter] a = self(letter)[0] @@ -1859,7 +1859,7 @@ def periodic_point(self, letter): cycle.append(a) a = self(a)[0] if a != letter: - raise ValueError, "there is no periodic point starting with letter (=%s)"%letter + raise ValueError("there is no periodic point starting with letter (=%s)"%letter) return (self**len(cycle)).fixed_point(letter) def periodic_points(self): @@ -1904,7 +1904,7 @@ def periodic_points(self): assert self.is_endomorphism(), "f should be an endomorphism" if self.is_erasing(): - raise NotImplementedError, "f should be non erasing" + raise NotImplementedError("f should be non erasing") A = self.domain().alphabet() d = dict((letter,self(letter)[0]) for letter in A) @@ -2314,7 +2314,7 @@ def rauzy_fractal_projection(self, eig=None, prec=53): # Test is deg(beta) >= 2 if beta.degree() < 2: - raise ValueError, "The algebraic degree of ``eig`` must be at least two." + raise ValueError("The algebraic degree of ``eig`` must be at least two.") # Algebraic conjugates of beta from sage.rings.qqbar import QQbar @@ -2810,7 +2810,7 @@ def is_growing(self, letter=None): I = range(self.domain().alphabet().cardinality()) else: if not letter in self.domain().alphabet(): - raise TypeError, "letter (=%s) is not in the domain of self"%letter + raise TypeError("letter (=%s) is not in the domain of self"%letter) I = [self.domain().alphabet().rank(letter)] last_coef = 0 diff --git a/src/sage/combinat/words/paths.py b/src/sage/combinat/words/paths.py index 68c258f85ff..d539b732f46 100644 --- a/src/sage/combinat/words/paths.py +++ b/src/sage/combinat/words/paths.py @@ -325,7 +325,7 @@ def WordPaths(alphabet, steps=None): elif alphabet.cardinality() == 6: steps = 'hexagonal_grid' else: - raise TypeError, "Unable to make a class WordPaths from %s"%alphabet + raise TypeError("Unable to make a class WordPaths from %s"%alphabet) #Returns the class of WordPaths according to the given type of paths if isinstance(steps, str): @@ -342,7 +342,7 @@ def WordPaths(alphabet, steps=None): elif steps == 'dyck': return WordPaths_dyck(alphabet=alphabet) else: - raise TypeError, "Unknown type of steps : %s"%steps + raise TypeError("Unknown type of steps : %s"%steps) else: return WordPaths_all(alphabet=alphabet, steps=steps) @@ -414,8 +414,8 @@ def __init__(self, alphabet, steps): ls = len(steps) la = alphabet.cardinality() if la != ls and la != 2*ls: - raise TypeError,"size of steps (=%s) must equal the size \ -of alphabet (=%s) or half the size of alphabet."%(len(steps),alphabet.cardinality()) + raise TypeError("size of steps (=%s) must equal the size \ +of alphabet (=%s) or half the size of alphabet."%(len(steps),alphabet.cardinality())) #Construction of the steps from sage.structure.element import Vector @@ -425,11 +425,11 @@ def __init__(self, alphabet, steps): try: vsteps = map(vector, steps) except (TypeError): - raise ValueError, "Can't make vectors from steps" + raise ValueError("Can't make vectors from steps") try: s = sum(vsteps) except (TypeError, AttributeError): - raise ValueError, "Can't make summable vectors from steps" + raise ValueError("Can't make summable vectors from steps") #Complete vsteps with the opposite vectors if needed if la == 2 * ls: @@ -1404,7 +1404,7 @@ def plot_projection(self, v=None, letters=None, color=None, ring=None, dimension = self.parent().vector_space().dimension() if not dimension in (3, 4): msg = "The dimension of the vector space (=%s) must be 3 or 4"%dimension - raise TypeError, msg + raise TypeError(msg) if letters is None: letters = self.parent().alphabet() if color is None: @@ -1415,7 +1415,7 @@ def plot_projection(self, v=None, letters=None, color=None, ring=None, if kind is 'right': start = it.next() elif kind is not 'left': - raise ValueError, 'unknown value for kind (=%s)'%kind + raise ValueError('unknown value for kind (=%s)'%kind) tout = [point([c], color=color[a], size=size) for a, c in izip(self, it) if a in letters] return sum(tout) @@ -1738,7 +1738,7 @@ def area(self): """ if not self.is_closed(): - raise TypeError, "the path must be closed to compute its area" + raise TypeError("the path must be closed to compute its area") return NotImplemented def height(self): @@ -2058,7 +2058,7 @@ def area(self): """ if not self.is_closed(): - raise TypeError, "the path must be closed to compute its area" + raise TypeError("the path must be closed to compute its area") return abs(self._area_vh()) def _area_vh(path, x=0, y=0): diff --git a/src/sage/combinat/words/suffix_trees.py b/src/sage/combinat/words/suffix_trees.py index 023e5c3f28e..68837ae1a05 100644 --- a/src/sage/combinat/words/suffix_trees.py +++ b/src/sage/combinat/words/suffix_trees.py @@ -349,11 +349,11 @@ def suffix_link(self, state): TypeError: 17 is not a state """ if not isinstance(state, (int,Integer)): - raise TypeError, "%s is not an integer" % state + raise TypeError("%s is not an integer" % state) if state == -1: - raise TypeError, "suffix link is not defined for -1" + raise TypeError("suffix link is not defined for -1") if state not in range(len(self._suffix_link)): - raise TypeError, "%s is not a state" % state + raise TypeError("%s is not a state" % state) return self._suffix_link[state] def active_state(self): @@ -1023,7 +1023,7 @@ def suffix_link(self, state): if state in self._suffix_link: return self._suffix_link[state] else: - raise TypeError, "there is no suffix link from %s" % state + raise TypeError("there is no suffix link from %s" % state) def active_state(self): r""" @@ -1205,7 +1205,7 @@ def number_of_factors(self,n=None): else: queue.append((u,l+j-i+1)) else: - raise TypeError, "not an integer or None: %s" %s + raise TypeError("not an integer or None: %s" %s) return num_factors def factor_iterator(self,n=None): @@ -1273,7 +1273,7 @@ def factor_iterator(self,n=None): else: queue.append((u,w*self.word()[i-1:j])) else: - raise TypeError, "not an integer or None: %s" %s + raise TypeError("not an integer or None: %s" %s) ##### # Miscellaneous methods diff --git a/src/sage/combinat/words/word_generators.py b/src/sage/combinat/words/word_generators.py index 783ca25ba88..ec3be815a82 100644 --- a/src/sage/combinat/words/word_generators.py +++ b/src/sage/combinat/words/word_generators.py @@ -176,10 +176,10 @@ def __init__(self, p, q, alphabet=(0,1), algorithm='cf'): sage: _ = w2.standard_factorization() # hackish test for self.__p and self.__q """ if len(set(alphabet)) != 2: - raise ValueError, "alphabet must contain exactly two distinct elements" + raise ValueError("alphabet must contain exactly two distinct elements") # Compute gcd of p, q; raise TypeError if not 1. if gcd(p,q) != 1: - raise ValueError, "%s and %s are not relatively prime" % (p, q) + raise ValueError("%s and %s are not relatively prime" % (p, q)) # Compute the Christoffel word if algorithm == 'linear': w = [] @@ -216,7 +216,7 @@ def __init__(self, p, q, alphabet=(0,1), algorithm='cf'): v = u * (cf[i]-1) + v w = u + v else: - raise ValueError, 'Unknown algorithm (=%s)'%algorithm + raise ValueError('Unknown algorithm (=%s)'%algorithm) super(LowerChristoffelWord, self).__init__(Words(alphabet), w) self.__p = p self.__q = q @@ -419,7 +419,7 @@ def ThueMorseWord(self, alphabet=(0, 1), base=2): alphabet = w.parent().alphabet() m = w.parent().size_of_alphabet() if base < 2 or m < 2 : - raise ValueError, "base (=%s) and size of alphabet (=%s) must be at least 2"%(base, m) + raise ValueError("base (=%s) and size of alphabet (=%s) must be at least 2"%(base, m)) return w def _ThueMorseWord_nth_digit(self, n, alphabet=(0,1), base=2): @@ -466,7 +466,7 @@ def _ThueMorseWord_nth_digit(self, n, alphabet=(0,1), base=2): NotImplementedError: nth digit of Thue-Morse word is not implemented for negative value of n """ if n < 0: - raise NotImplementedError, "nth digit of Thue-Morse word is not implemented for negative value of n" + raise NotImplementedError("nth digit of Thue-Morse word is not implemented for negative value of n") m = len(alphabet) if base == 2 and m == 2: for tn in count(): @@ -474,7 +474,7 @@ def _ThueMorseWord_nth_digit(self, n, alphabet=(0,1), base=2): return alphabet[tn & 1] n &= n - 1 elif base < 2 or m < 2 : - raise ValueError, "base (=%s) and len(alphabet) (=%s) must be at least 2"%(base, m) + raise ValueError("base (=%s) and len(alphabet) (=%s) must be at least 2"%(base, m)) else: return alphabet[ZZ(sum(ZZ(n).digits(base = base))).mod(m)] @@ -681,7 +681,7 @@ def CodingOfRotationWord(self, alpha, beta, x=0, alphabet=(0,1)): TypeError: alphabet does not contain two distinct elements """ if len(set(alphabet)) != 2: - raise TypeError, "alphabet does not contain two distinct elements" + raise TypeError("alphabet does not contain two distinct elements") from functools import partial f = partial(self._CodingOfRotationWord_function,alpha=alpha,beta=beta,x=x,alphabet=alphabet) w = Words(alphabet)(f, datatype='callable') @@ -872,7 +872,7 @@ def CharacteristicSturmianWord(self, slope, alphabet=(0, 1), bits=None): if slope in RR: if not 0 < slope < 1: msg = "The argument slope (=%s) must be in ]0,1[."%slope - raise ValueError, msg + raise ValueError(msg) from sage.rings.all import CFF cf = iter(CFF(slope, bits=bits)) length = 'finite' @@ -928,12 +928,12 @@ def _CharacteristicSturmianWord_LetterIterator(self, cf, alphabet=(0,1)): word: 0100100101001001001010010010010100100101... """ if cf.next() != 0: - raise ValueError, "The first term of the continued fraction expansion must be zero." + raise ValueError("The first term of the continued fraction expansion must be zero.") s0 = [1] s1 = [0] e = cf.next() if not e >= 1: - raise ValueError, "The second term of the continued fraction expansion must be larger or equal to 1." + raise ValueError("The second term of the continued fraction expansion must be larger or equal to 1.") s1, s0 = s1*(e-1) + s0, s1 n = 0 while True: @@ -1018,7 +1018,7 @@ def KolakoskiWord(self, alphabet=(1,2)): a, b = alphabet if a not in ZZ or a <= 0 or b not in ZZ or b <= 0 or a == b: msg = 'The alphabet (=%s) must consist of two distinct positive integers'%(alphabet,) - raise ValueError, msg + raise ValueError(msg) return Words(alphabet)(self._KolakoskiWord_iterator(a, b), datatype = 'iter') def _KolakoskiWord_iterator(self, a=1, b=2): @@ -1254,7 +1254,7 @@ def StandardEpisturmianWord(self, directive_word): 2007, arXiv:0801.1655. """ if not isinstance(directive_word, Word_class): - raise TypeError, "directive_word is not a word, so it cannot be used to build an episturmian word" + raise TypeError("directive_word is not a word, so it cannot be used to build an episturmian word") epistandard = directive_word.parent()(\ self._StandardEpisturmianWord_LetterIterator(directive_word), \ datatype='iter') @@ -1382,7 +1382,7 @@ def RandomWord(self, n, m=2, alphabet=None): if alphabet is None: alphabet = range(m) if len(set(alphabet)) != m: - raise TypeError, "alphabet does not contain %s distinct elements" % m + raise TypeError("alphabet does not contain %s distinct elements" % m) return Words(alphabet)([alphabet[randint(0,m-1)] for i in xrange(n)]) LowerChristoffelWord = LowerChristoffelWord @@ -1628,7 +1628,7 @@ def _s_adic_iterator(self, sequence, letters): yield precedent_letter for (i,(m,a)) in enumerate(izip(sequence, letters)): if not precedent_letter == m(a)[0]: - raise ValueError, "The hypothesis of the algorithm used is not satisfied: the image of the %s-th letter (=%s) under the %s-th morphism (=%s) should start with the %s-th letter (=%s)."%(i+1,a,i+1,m,i,precedent_letter) + raise ValueError("The hypothesis of the algorithm used is not satisfied: the image of the %s-th letter (=%s) under the %s-th morphism (=%s) should start with the %s-th letter (=%s)."%(i+1,a,i+1,m,i,precedent_letter)) w = p(m(a)[1:]) for b in w: yield b @@ -1874,7 +1874,7 @@ def s_adic(self, sequence, letters, morphisms=None): elif hasattr(morphisms, '__call__'): seq = (morphisms(i) for i in sequence) else: - raise TypeError, "morphisms (=%s) must be None, callable or provide a __getitem__ method."%morphisms + raise TypeError("morphisms (=%s) must be None, callable or provide a __getitem__ method."%morphisms) from sage.combinat.words.word import FiniteWord_class if isinstance(sequence,(tuple,list,str,FiniteWord_class)) \ diff --git a/src/sage/combinat/words/word_infinite_datatypes.py b/src/sage/combinat/words/word_infinite_datatypes.py index fa1557c8af7..f3b5e08e68a 100644 --- a/src/sage/combinat/words/word_infinite_datatypes.py +++ b/src/sage/combinat/words/word_infinite_datatypes.py @@ -236,7 +236,7 @@ def __getitem__(self, key): if self._len is Infinity: if not(key.start is None) and key.start < 0 or \ not(key.stop is None) and key.stop < 0: - raise ValueError, "for infinite words, start and stop values cannot be negative" + raise ValueError("for infinite words, start and stop values cannot be negative") step = 1 if key.step is None else key.step if step > 0: start = 0 if key.start is None else key.start @@ -244,7 +244,7 @@ def __getitem__(self, key): int(max(0,ceil((key.stop-start)/float(step)))) else: if key.start is None or key.start < 0: - raise ValueError, "start value must be nonnegative for negative step values" + raise ValueError("start value must be nonnegative for negative step values") start = key.start stop = 0 if key.stop is None else key.stop length = int(max(0,ceil((key.stop-start)/float(step)))) @@ -268,11 +268,11 @@ def __getitem__(self, key): else: if key < 0: if self._len is Infinity: - raise IndexError, "cannot use a negative index with an infinite word" + raise IndexError("cannot use a negative index with an infinite word") else: key = self._len + key elif key >= self._len: - raise IndexError, "word index out of range" + raise IndexError("word index out of range") return self._func(key) def __reduce__(self): @@ -796,7 +796,7 @@ def __getitem__(self, key): if self._len is Infinity: if not(key.start is None) and key.start < 0 or \ not(key.stop is None) and key.stop < 0: - raise ValueError, "for infinite words, start and stop values cannot be negative" + raise ValueError("for infinite words, start and stop values cannot be negative") step = 1 if key.step is None else key.step if step >= 0: start = 0 if key.start is None else key.start @@ -808,7 +808,7 @@ def __getitem__(self, key): return self._parent(data, length=length) else: if key.start is None or key.start < 0: - raise ValueError, "start value must be nonnegative for negative step values" + raise ValueError("start value must be nonnegative for negative step values") start = key.start stop = 0 if key.stop is None else key.stop length = int(max(0,ceil((key.stop-start)/float(step)))) @@ -837,9 +837,9 @@ def __getitem__(self, key): else: if key < 0: if self._len is Infinity: - raise IndexError, "cannot use negative indices with infinite words" + raise IndexError("cannot use negative indices with infinite words") elif self._len is None: - raise IndexError, "cannot use negative indices with words of unknown length" + raise IndexError("cannot use negative indices with words of unknown length") else: key = self.length() + key it = iter(self) @@ -850,7 +850,7 @@ def __getitem__(self, key): a = it.next() counter += 1 except StopIteration: - raise IndexError, "word index out of range" + raise IndexError("word index out of range") return a def __reduce__(self): @@ -1125,7 +1125,7 @@ def __getitem__(self, key): self._list.append(self._gen.next()) self._last_index += 1 except StopIteration: - raise IndexError, "word index out of range" + raise IndexError("word index out of range") return self._list[key] def __reduce__(self): diff --git a/src/sage/combinat/words/word_options.py b/src/sage/combinat/words/word_options.py index d5c0c373480..e49946a9deb 100644 --- a/src/sage/combinat/words/word_options.py +++ b/src/sage/combinat/words/word_options.py @@ -64,36 +64,36 @@ def WordOptions(**kwargs): return copy.copy(word_options) if 'display' in kwargs: if kwargs['display'] not in ['list', 'string']: - raise ValueError, "display must be either 'list' or 'string'" + raise ValueError("display must be either 'list' or 'string'") else: word_options['display'] = kwargs['display'] elif 'truncate' in kwargs: if not isinstance(kwargs['truncate'], bool): - raise ValueError, "truncate must be True or False" + raise ValueError("truncate must be True or False") else: word_options['truncate'] = kwargs['truncate'] elif 'truncate_length' in kwargs: if not isinstance(kwargs['truncate_length'], (int,Integer)) or kwargs['truncate_length'] <= 0: - raise ValueError, "truncate_length must be a positive integer" + raise ValueError("truncate_length must be a positive integer") else: word_options['truncate_length'] = kwargs['truncate_length'] elif 'letter_separator' in kwargs: if not isinstance(kwargs['letter_separator'], str): - raise ValueError, "letter_separator must be a string" + raise ValueError("letter_separator must be a string") else: word_options['letter_separator'] = kwargs['letter_separator'] elif 'identifier' in kwargs: if not isinstance(kwargs['identifier'], str): - raise ValueError, "identifier must be a string" + raise ValueError("identifier must be a string") else: word_options['identifier'] = kwargs['identifier'] elif 'cache' in kwargs: if not isinstance(kwargs['cache'], bool): - raise ValueError, "cache must be True or False" + raise ValueError("cache must be True or False") else: word_options['cache'] = kwargs['cache'] elif 'old_repr' in kwargs: if not isinstance(kwargs['old_repr'], bool): - raise ValueError, "old_repr must be True or False" + raise ValueError("old_repr must be True or False") else: word_options['old_repr'] = kwargs['old_repr'] diff --git a/src/sage/combinat/words/words.py b/src/sage/combinat/words/words.py index d95dafd78dc..5891b995300 100644 --- a/src/sage/combinat/words/words.py +++ b/src/sage/combinat/words/words.py @@ -108,7 +108,7 @@ def Words(alphabet=None, length=None, finite=True, infinite=True): return InfiniteWords_over_OrderedAlphabet(alphabet) elif isinstance(length, (int,Integer)): return FiniteWords_length_k_over_OrderedAlphabet(alphabet, length) - raise ValueError, "do not know how to make a combinatorial class of words from your input" + raise ValueError("do not know how to make a combinatorial class of words from your input") from sage.structure.unique_representation import UniqueRepresentation class Words_all(InfiniteAbstractCombinatorialClass): @@ -475,7 +475,7 @@ def _construct_word(self, data=None, length=None, datatype=None, caching=True): elif isinstance(data, WordDatatype): data = data._data else: - raise TypeError, "Any instance of Word_class must be an instance of WordDatatype." + raise TypeError("Any instance of Word_class must be an instance of WordDatatype.") if data is None: data = [] @@ -493,16 +493,16 @@ def _construct_word(self, data=None, length=None, datatype=None, caching=True): elif hasattr(data,"__iter__"): datatype = "iter" else: - raise ValueError, "Cannot guess a datatype from data (=%s); please specify one"%data + raise ValueError("Cannot guess a datatype from data (=%s); please specify one"%data) else: # type check the datatypes if datatype == "iter" and not hasattr(data, "__iter__"): - raise ValueError, "Your data is not iterable" + raise ValueError("Your data is not iterable") elif datatype == "callable" and not callable(data): - raise ValueError, "Your data is not callable" + raise ValueError("Your data is not callable") elif datatype not in ("list", "tuple", "str", "callable", "iter", "pickled_function"): - raise ValueError, "Unknown datatype (=%s)" % datatype + raise ValueError("Unknown datatype (=%s)" % datatype) # If `data` is a pickled_function, restore the function if datatype == 'pickled_function': @@ -532,12 +532,12 @@ def _construct_word(self, data=None, length=None, datatype=None, caching=True): elif length in ZZ and length >= 0: cls_str = 'FiniteWord_iter' else: - raise ValueError, "not a correct value for length (%s)" % length + raise ValueError("not a correct value for length (%s)" % length) if caching: cls_str += '_with_caching' kwds = dict(parent=self,iter=data,length=length) else: - raise ValueError, "Not known datatype" + raise ValueError("Not known datatype") wordclass = self._element_classes cls = wordclass[cls_str] @@ -569,7 +569,7 @@ def _check(self, w, length=40): """ for a in itertools.islice(w, length): if a not in self._alphabet: - raise ValueError, "%s not in alphabet!" % a + raise ValueError("%s not in alphabet!" % a) def _repr_(self): """ @@ -884,7 +884,7 @@ def identity_morphism(self): NotImplementedError: size of alphabet must be finite """ if self.size_of_alphabet() not in ZZ: - raise NotImplementedError, 'size of alphabet must be finite' + raise NotImplementedError('size of alphabet must be finite') from sage.combinat.words.morphism import WordMorphism return WordMorphism(dict((a,a) for a in self.alphabet())) @@ -975,7 +975,7 @@ def iterate_by_length(self, l=1): TypeError: the parameter l (='a') must be an integer """ if not isinstance(l, (int,Integer)): - raise TypeError, "the parameter l (=%r) must be an integer"%l + raise TypeError("the parameter l (=%r) must be an integer"%l) #if l == Integer(0): # yield self() for w in xmrange([self.size_of_alphabet()]*l): @@ -1260,7 +1260,7 @@ def iter_morphisms(self, arg=None, codomain=None, min_length=1): if codomain is None: codomain = self elif not isinstance(codomain, Words_over_OrderedAlphabet): - raise TypeError, "codomain (=%s) must be an instance of Words_over_OrderedAlphabet"%codomain + raise TypeError("codomain (=%s) must be an instance of Words_over_OrderedAlphabet"%codomain) # iterate through the morphisms from sage.combinat.words.morphism import WordMorphism diff --git a/src/sage/crypto/block_cipher/miniaes.py b/src/sage/crypto/block_cipher/miniaes.py index af9f7d0a40b..b563e695740 100644 --- a/src/sage/crypto/block_cipher/miniaes.py +++ b/src/sage/crypto/block_cipher/miniaes.py @@ -354,13 +354,13 @@ def __call__(self, B, key, algorithm="encrypt"): """ from sage.rings.finite_rings.integer_mod import Mod if not isinstance(B, StringMonoidElement): - raise TypeError, "input B must be a non-empty binary string with number of bits a multiple of 16" + raise TypeError("input B must be a non-empty binary string with number of bits a multiple of 16") if (len(B) == 0) or (Mod(len(B), self._key_size).lift() != 0): - raise ValueError, "the number of bits in the binary string B must be positive and a multiple of 16" + raise ValueError("the number of bits in the binary string B must be positive and a multiple of 16") if not isinstance(key, StringMonoidElement): - raise TypeError, "secret key must be a 16-bit binary string" + raise TypeError("secret key must be a 16-bit binary string") if len(key) != self._key_size: - raise ValueError, "secret key must be a 16-bit binary string" + raise ValueError("secret key must be a 16-bit binary string") N = len(B) / self._key_size # the number of 16-bit blocks MS = MatrixSpace(FiniteField(self._key_size, "x"), 2, 2) @@ -389,7 +389,7 @@ def __call__(self, B, key, algorithm="encrypt"): S = "".join([S, str(e)]) return bin(S) else: - raise ValueError, "algorithm must be either 'encrypt' or 'decrypt'" + raise ValueError("algorithm must be either 'encrypt' or 'decrypt'") def __eq__(self, other): r""" @@ -538,15 +538,15 @@ def add_key(self, block, rkey): """ if not isinstance(block, Matrix_dense) or \ not (block.base_ring().order() == 16 and block.base_ring().is_field()): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") if not (block.nrows() == block.ncols() == 2): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") if not isinstance(rkey, Matrix_dense) or \ not (rkey.base_ring().order() == 16 and rkey.base_ring().is_field()): - raise TypeError, "round key must be a 2 x 2 matrix over GF(16)" + raise TypeError("round key must be a 2 x 2 matrix over GF(16)") if not (rkey.nrows() == rkey.ncols() == 2): - raise TypeError, "round key must be a 2 x 2 matrix over GF(16)" + raise TypeError("round key must be a 2 x 2 matrix over GF(16)") return block + rkey @@ -710,14 +710,14 @@ def decrypt(self, C, key): """ if not isinstance(C, Matrix_dense) or \ not (C.base_ring().order() == 16 and C.base_ring().is_field()): - raise TypeError, "ciphertext block must be a 2 x 2 matrix over GF(16)" + raise TypeError("ciphertext block must be a 2 x 2 matrix over GF(16)") if not (C.nrows() == C.ncols() == 2): - raise TypeError, "ciphertext block must be a 2 x 2 matrix over GF(16)" + raise TypeError("ciphertext block must be a 2 x 2 matrix over GF(16)") if not isinstance(key, Matrix_dense) or \ not (key.base_ring().order() == 16 and key.base_ring().is_field()): - raise TypeError, "secret key must be a 2 x 2 matrix over GF(16)" + raise TypeError("secret key must be a 2 x 2 matrix over GF(16)") if not (key.nrows() == key.ncols() == 2): - raise TypeError, "secret key must be a 2 x 2 matrix over GF(16)" + raise TypeError("secret key must be a 2 x 2 matrix over GF(16)") # pre-compute the round keys rkey0 = self.round_key(key, 0) @@ -871,14 +871,14 @@ def encrypt(self, P, key): """ if not isinstance(P, Matrix_dense) or \ not (P.base_ring().order() == 16 and P.base_ring().is_field()): - raise TypeError, "plaintext block must be a 2 x 2 matrix over GF(16)" + raise TypeError("plaintext block must be a 2 x 2 matrix over GF(16)") if not (P.nrows() == P.ncols() == 2): - raise TypeError, "plaintext block must be a 2 x 2 matrix over GF(16)" + raise TypeError("plaintext block must be a 2 x 2 matrix over GF(16)") if not isinstance(key, Matrix_dense) or \ not (key.base_ring().order() == 16 and key.base_ring().is_field()): - raise TypeError, "secret key must be a 2 x 2 matrix over GF(16)" + raise TypeError("secret key must be a 2 x 2 matrix over GF(16)") if not (key.nrows() == key.ncols() == 2): - raise TypeError, "secret key must be a 2 x 2 matrix over GF(16)" + raise TypeError("secret key must be a 2 x 2 matrix over GF(16)") # pre-compute the round keys rkey0 = self.round_key(key, 0) @@ -1025,9 +1025,9 @@ def mix_column(self, block): """ if not isinstance(block, Matrix_dense) or \ not (block.base_ring().order() == 16 and block.base_ring().is_field()): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") if not (block.nrows() == block.ncols() == 2): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") K = FiniteField(self._key_size, "x") MS = MatrixSpace(K, 2, 2) @@ -1216,9 +1216,9 @@ def nibble_sub(self, block, algorithm="encrypt"): """ if not isinstance(block, Matrix_dense) or \ not (block.base_ring().order() == 16 and block.base_ring().is_field()): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") if not (block.nrows() == block.ncols() == 2): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") MS = MatrixSpace(FiniteField(self._key_size, "x"), 2, 2) # get the integer representation of each GF(2^4) element @@ -1235,7 +1235,7 @@ def nibble_sub(self, block, algorithm="encrypt"): # to an element of GF(2^4). return MS([self._int_to_GF[self._sboxD[e]] for e in lst]) else: - raise ValueError, "the algorithm for nibble-sub must be either 'encrypt' or 'decrypt'" + raise ValueError("the algorithm for nibble-sub must be either 'encrypt' or 'decrypt'") def random_key(self): r""" @@ -1360,9 +1360,9 @@ def round_key(self, key, n): """ if not isinstance(key, Matrix_dense) or \ not (key.base_ring().order() == 16 and key.base_ring().is_field()): - raise TypeError, "secret key must be a 2 x 2 matrix over GF(16)" + raise TypeError("secret key must be a 2 x 2 matrix over GF(16)") if not (key.nrows() == key.ncols() == 2): - raise TypeError, "secret key must be a 2 x 2 matrix over GF(16)" + raise TypeError("secret key must be a 2 x 2 matrix over GF(16)") K = FiniteField(self._key_size, "x") MS = MatrixSpace(K, 2, 2) @@ -1388,7 +1388,7 @@ def round_key(self, key, n): return MS([ [w8, w10], [w9, w11] ]) # unsupported round number if (n < 0) or (n > 2): - raise ValueError, "Mini-AES only defines two rounds" + raise ValueError("Mini-AES only defines two rounds") def sbox(self): r""" @@ -1510,9 +1510,9 @@ def shift_row(self, block): """ if not isinstance(block, Matrix_dense) or \ not (block.base_ring().order() == 16 and block.base_ring().is_field()): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") if not (block.nrows() == block.ncols() == 2): - raise TypeError, "input block must be a 2 x 2 matrix over GF(16)" + raise TypeError("input block must be a 2 x 2 matrix over GF(16)") MS = MatrixSpace(FiniteField(self._key_size, "x"), 2, 2) mat = MS([ [block[0][0], block[0][1]], @@ -1659,18 +1659,18 @@ def GF_to_binary(self, G): # G is a list of elements over GF(16) elif isinstance(G, list): if len(G) == 0: - raise ValueError, "input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)" + raise ValueError("input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)") S = "".join([str(self._GF_to_bin[g]) for g in G]) return B(S) # G is a matrix over GF(16) elif isinstance(G, Matrix_dense): if not (G.base_ring() is K): - raise TypeError, "input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)" + raise TypeError("input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)") S = "".join([str(self._GF_to_bin[G[i][j]]) for i in xrange(G.nrows()) for j in xrange(G.ncols())]) return B(S) # the type of G doesn't match the supported types else: - raise TypeError, "input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)" + raise TypeError("input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)") def GF_to_integer(self, G): r""" @@ -1791,16 +1791,16 @@ def GF_to_integer(self, G): # G is a list of elements over GF(16) elif isinstance(G, list): if len(G) == 0: - raise ValueError, "input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)" + raise ValueError("input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)") return [self._GF_to_int[g] for g in G] # G is a matrix over GF(16) elif isinstance(G, Matrix_dense): if not (G.base_ring() is K): - raise TypeError, "input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)" + raise TypeError("input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)") return [self._GF_to_int[G[i][j]] for i in xrange(G.nrows()) for j in xrange(G.ncols())] # the type of G doesn't match the supported types else: - raise TypeError, "input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)" + raise TypeError("input G must be an element of GF(16), a list of elements of GF(16), or a matrix over GF(16)") def binary_to_GF(self, B): r""" @@ -1882,13 +1882,13 @@ def binary_to_GF(self, B): b = bin(B) # an empty string if len(b) == 0: - raise ValueError, "the number of bits in the binary string B must be positive and a multiple of 4" + raise ValueError("the number of bits in the binary string B must be positive and a multiple of 4") # a string with number of bits that is a multiple of 4 if Mod(len(b), 4).lift() == 0: M = len(b) / 4 # the number of nibbles return [self._bin_to_GF[b[i*4 : (i+1)*4]] for i in xrange(M)] else: - raise ValueError, "the number of bits in the binary string B must be positive and a multiple of 4" + raise ValueError("the number of bits in the binary string B must be positive and a multiple of 4") def binary_to_integer(self, B): r""" @@ -1952,13 +1952,13 @@ def binary_to_integer(self, B): b = bin(B) # an empty string if len(b) == 0: - raise ValueError, "the number of bits in the binary string B must be positive and a multiple of 4" + raise ValueError("the number of bits in the binary string B must be positive and a multiple of 4") # a string with number of bits that is a multiple of 4 if Mod(len(b), 4).lift() == 0: M = len(b) / 4 # the number of nibbles return [self._bin_to_int[b[i*4 : (i+1)*4]] for i in xrange(M)] else: - raise ValueError, "the number of bits in the binary string B must be positive and a multiple of 4" + raise ValueError("the number of bits in the binary string B must be positive and a multiple of 4") def integer_to_binary(self, N): r""" @@ -2058,7 +2058,7 @@ def integer_to_binary(self, N): """ if isinstance(N, list): if len(N) == 0: - raise ValueError, "N must be an integer 0 <= N <= 15 or a list of such integers" + raise ValueError("N must be an integer 0 <= N <= 15 or a list of such integers") bin = BinaryStrings() # Here, we assume that each element of the list is an integer n # such that 0 <= n <= 15. An error will be raised if otherwise. @@ -2069,7 +2069,7 @@ def integer_to_binary(self, N): # An error will be raised if otherwise. return self._int_to_bin[N] else: - raise TypeError, "N must be an integer 0 <= N <= 15 or a list of such integers" + raise TypeError("N must be an integer 0 <= N <= 15 or a list of such integers") def integer_to_GF(self, N): r""" @@ -2187,7 +2187,7 @@ def integer_to_GF(self, N): """ if isinstance(N, list): if len(N) == 0: - raise ValueError, "N must be an integer 0 <= N <= 15 or a list of such integers" + raise ValueError("N must be an integer 0 <= N <= 15 or a list of such integers") # Here, we assume that each element of the list is an integer n # such that 0 <= n <= 15. An error will be raised if otherwise. return [self._int_to_GF[n] for n in N] @@ -2196,4 +2196,4 @@ def integer_to_GF(self, N): # An error will be raised if otherwise. return self._int_to_GF[N] else: - raise TypeError, "N must be an integer 0 <= N <= 15 or a list of such integers" + raise TypeError("N must be an integer 0 <= N <= 15 or a list of such integers") diff --git a/src/sage/crypto/block_cipher/sdes.py b/src/sage/crypto/block_cipher/sdes.py index 07eccfb6524..dd431dcedea 100644 --- a/src/sage/crypto/block_cipher/sdes.py +++ b/src/sage/crypto/block_cipher/sdes.py @@ -202,13 +202,13 @@ def __call__(self, B, K, algorithm="encrypt"): Blength = 8 if not isinstance(B, StringMonoidElement): - raise TypeError, "input B must be a non-empty binary string with number of bits a multiple of 8" + raise TypeError("input B must be a non-empty binary string with number of bits a multiple of 8") if (len(B) == 0) or (Mod(len(B), Blength).lift() != 0): - raise ValueError, "the number of bits in the binary string B must be positive and a multiple of 8" + raise ValueError("the number of bits in the binary string B must be positive and a multiple of 8") if not isinstance(K, StringMonoidElement): - raise TypeError, "secret key must be a 10-bit binary string" + raise TypeError("secret key must be a 10-bit binary string") if len(K) != self._key_size: - raise ValueError, "secret key must be a 10-bit binary string" + raise ValueError("secret key must be a 10-bit binary string") N = len(B) / Blength # the number of 8-bit blocks S = "" @@ -241,7 +241,7 @@ def __call__(self, B, K, algorithm="encrypt"): return bin(S) # invalid value for algorithm option else: - raise ValueError, "algorithm must be either 'encrypt' or 'decrypt'" + raise ValueError("algorithm must be either 'encrypt' or 'decrypt'") def __eq__(self, other): r""" @@ -384,13 +384,13 @@ def decrypt(self, C, K): """ # sanity check if not isinstance(C, list): - raise TypeError, "ciphertext must be a list of 8 bits" + raise TypeError("ciphertext must be a list of 8 bits") if len(C) != 8: - raise ValueError, "ciphertext must be a list of 8 bits" + raise ValueError("ciphertext must be a list of 8 bits") if not isinstance(K, list): - raise TypeError, "the key must be a list of 10 bits" + raise TypeError("the key must be a list of 10 bits") if len(K) != 10: - raise TypeError, "the key must be a list of 10 bits" + raise TypeError("the key must be a list of 10 bits") # run through initial permutation P = self.initial_permutation(C, inverse=False) @@ -498,13 +498,13 @@ def encrypt(self, P, K): """ # sanity check if not isinstance(P, list): - raise TypeError, "plaintext must be a list of 8 bits" + raise TypeError("plaintext must be a list of 8 bits") if len(P) != 8: - raise ValueError, "plaintext must be a list of 8 bits" + raise ValueError("plaintext must be a list of 8 bits") if not isinstance(K, list): - raise TypeError, "the key must be a list of 10 bits" + raise TypeError("the key must be a list of 10 bits") if len(K) != 10: - raise TypeError, "the key must be a list of 10 bits" + raise TypeError("the key must be a list of 10 bits") # run through initial permutation C = self.initial_permutation(P, inverse=False) @@ -612,9 +612,9 @@ def initial_permutation(self, B, inverse=False): """ # sanity check if not isinstance(B, list): - raise TypeError, "input block must be a list of 8 bits" + raise TypeError("input block must be a list of 8 bits") if len(B) != 8: - raise ValueError, "input block must be a list of 8 bits" + raise ValueError("input block must be a list of 8 bits") bin = BinaryStrings() @@ -739,9 +739,9 @@ def left_shift(self, B, n=1): """ # sanity check if not isinstance(B, list): - raise TypeError, "input block must be a list of 10 bits" + raise TypeError("input block must be a list of 10 bits") if len(B) != 10: - raise ValueError, "input block must be a list of 10 bits" + raise ValueError("input block must be a list of 10 bits") bin = BinaryStrings() # circular left shift by 1 position @@ -760,7 +760,7 @@ def left_shift(self, B, n=1): bin(str(B[5])), bin(str(B[6])) ] # an invalid number of shift positions else: - raise ValueError, "input n must be either 1 or 2" + raise ValueError("input n must be either 1 or 2") def list_to_string(self, B): r""" @@ -808,9 +808,9 @@ def list_to_string(self, B): """ # sanity check if not isinstance(B, list): - raise TypeError, "input B must be a non-empty list of bits" + raise TypeError("input B must be a non-empty list of bits") if len(B) == 0: - raise ValueError, "input B must be a non-empty list of bits" + raise ValueError("input B must be a non-empty list of bits") # perform the conversion from list to binary string from sage.rings.integer import Integer @@ -892,9 +892,9 @@ def permutation4(self, B): """ # sanity check if not isinstance(B, list): - raise TypeError, "input block must be a list of 4 bits" + raise TypeError("input block must be a list of 4 bits") if len(B) != 4: - raise ValueError, "input block must be a list of 4 bits" + raise ValueError("input block must be a list of 4 bits") # perform the permutation bin = BinaryStrings() @@ -981,9 +981,9 @@ def permutation8(self, B): """ # sanity check if not isinstance(B, list): - raise TypeError, "input block must be a list of 10 bits" + raise TypeError("input block must be a list of 10 bits") if len(B) != 10: - raise ValueError, "input block must be a list of 10 bits" + raise ValueError("input block must be a list of 10 bits") # perform the permutation bin = BinaryStrings() @@ -1071,9 +1071,9 @@ def permutation10(self, B): """ # sanity check if not isinstance(B, list): - raise TypeError, "input block must be a list of 10 bits" + raise TypeError("input block must be a list of 10 bits") if len(B) != 10: - raise ValueError, "input block must be a list of 10 bits" + raise ValueError("input block must be a list of 10 bits") # perform the permutation bin = BinaryStrings() @@ -1249,13 +1249,13 @@ def permute_substitute(self, B, key): """ # sanity check if not isinstance(B, list): - raise TypeError, "input B must be an 8-bit string" + raise TypeError("input B must be an 8-bit string") if len(B) != 8: - raise ValueError, "input B must be an 8-bit string" + raise ValueError("input B must be an 8-bit string") if not isinstance(key, list): - raise TypeError, "input key must be an 8-bit subkey" + raise TypeError("input key must be an 8-bit subkey") if len(key) != 8: - raise ValueError, "input key must be an 8-bit subkey" + raise ValueError("input key must be an 8-bit subkey") from sage.rings.finite_rings.constructor import FiniteField GF = FiniteField(2, "x") @@ -1363,9 +1363,9 @@ def string_to_list(self, S): """ # sanity check if not isinstance(S, str): - raise TypeError, "input S must be a non-empty string of bits" + raise TypeError("input S must be a non-empty string of bits") if len(S) == 0: - raise ValueError, "input S must be a non-empty string of bits" + raise ValueError("input S must be a non-empty string of bits") # perform the conversion from string to list bin = BinaryStrings() @@ -1442,9 +1442,9 @@ def subkey(self, K, n=1): """ # sanity check if not isinstance(K, list): - raise TypeError, "input K must be a 10-bit key" + raise TypeError("input K must be a 10-bit key") if len(K) != self._key_size: - raise ValueError, "input K must be a 10-bit key" + raise ValueError("input K must be a 10-bit key") # get the first subkey if n == 1: @@ -1459,7 +1459,7 @@ def subkey(self, K, n=1): return self.permutation8(key2) # an invalid subkey number else: - raise ValueError, "input n must be either 1 or 2" + raise ValueError("input n must be either 1 or 2") def switch(self, B): r""" @@ -1538,9 +1538,9 @@ def switch(self, B): """ # sanity check if not isinstance(B, list): - raise TypeError, "input block must be a list of 8 bits" + raise TypeError("input block must be a list of 8 bits") if len(B) != 8: - raise ValueError, "input block must be a list of 8 bits" + raise ValueError("input block must be a list of 8 bits") # perform the switch bin = BinaryStrings() diff --git a/src/sage/crypto/classical_cipher.py b/src/sage/crypto/classical_cipher.py index c409a5a9668..20b31736224 100644 --- a/src/sage/crypto/classical_cipher.py +++ b/src/sage/crypto/classical_cipher.py @@ -196,10 +196,10 @@ def __eq__(self, right): def __call__(self, M): S = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == S: - raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M + raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) m = self.parent().block_length() if len(M) % m != 0: - raise TypeError, "The length of M (= %s) must be a multiple of %s." % (M, m ) + raise TypeError("The length of M (= %s) must be a multiple of %s." % (M, m )) Alph = list(S.alphabet()) A = self.key() # A is an m x m matrix R = A.parent().base_ring() @@ -231,7 +231,7 @@ def inverse(self): try: B = E.inverse_key(self.key()) except Exception: - raise ValueError, "Argument\n\n%s\n\nmust be an invertible cipher." % self + raise ValueError("Argument\n\n%s\n\nmust be an invertible cipher." % self) return E(B) class ShiftCipher(SymmetricKeyCipher): @@ -419,7 +419,7 @@ def __eq__(self, right): def __call__(self, M): S = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == S: - raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M + raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) A = list(S.alphabet()) K = str(self.key()) # K is a string, while we want the indices: I = [ A.index(K[i]) for i in range(len(K)) ] @@ -501,20 +501,20 @@ def __init__(self, parent, key): """ n = parent.block_length() if isinstance(key, list) and not len(key) == n: - raise ValueError, "key (= %s) must have block length %s" % (key, n) + raise ValueError("key (= %s) must have block length %s" % (key, n)) SymmetricKeyCipher.__init__(self, parent, key) def __call__(self, M, mode = "ECB"): S = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == S: - raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M + raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) if not mode == "ECB": - raise NotImplementedError, "Enciphering not implemented for mode (= %s) other than 'ECB'." % mode + raise NotImplementedError("Enciphering not implemented for mode (= %s) other than 'ECB'." % mode) g = self.key() N = len(M) m = self.parent().block_length() if not N%m == 0: - raise TypeError, "Argument M (= %s) must be a string of length k*%s." % (M, m) + raise TypeError("Argument M (= %s) must be a string of length k*%s." % (M, m)) Melt = M._element_list # this uses the internal structure of string monoids # Caution: this is parsed as an outer loop in k and an inner loop in i: # for k in range(N//m): @@ -559,9 +559,9 @@ def __init__(self, parent, key): def __call__(self, M, mode = "ECB"): S = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == S: - raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M + raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) if not mode == "ECB": - raise NotImplementedError, "Enciphering not implemented for mode (= %s) other than 'ECB'." % mode + raise NotImplementedError("Enciphering not implemented for mode (= %s) other than 'ECB'." % mode) K = self.key() m = self.parent().period() n = S.ngens() diff --git a/src/sage/crypto/cryptosystem.py b/src/sage/crypto/cryptosystem.py index 98bb494840e..912c1ea8d1b 100644 --- a/src/sage/crypto/cryptosystem.py +++ b/src/sage/crypto/cryptosystem.py @@ -344,7 +344,7 @@ def block_length(self): def period(self): if self._period is None: - raise TypeError, "Argument has no associated period." + raise TypeError("Argument has no associated period.") return self._period class SymmetricKeyCryptosystem(Cryptosystem): diff --git a/src/sage/crypto/lfsr.py b/src/sage/crypto/lfsr.py index 7cd7028a927..aa154d500d5 100644 --- a/src/sage/crypto/lfsr.py +++ b/src/sage/crypto/lfsr.py @@ -203,11 +203,11 @@ def lfsr_sequence(key, fill, n): Cookbook, http://aspn.activestate.com/ASPN/Python/Cookbook/ """ if not isinstance(key, list): - raise TypeError, "key must be a list" + raise TypeError("key must be a list") key = Sequence(key) F = key.universe() if not is_FiniteField(F): - raise TypeError, "universe of sequence must be a finite field" + raise TypeError("universe of sequence must be a finite field") s = fill k = len(fill) @@ -251,7 +251,7 @@ def lfsr_autocorrelation(L, p, k): - Timothy Brock (2006-04-17) """ if not isinstance(L, list): - raise TypeError, "L (=%s) must be a list"%L + raise TypeError("L (=%s) must be a list"%L) p = Integer(p) _p = int(p) k = int(k) diff --git a/src/sage/crypto/mq/sbox.py b/src/sage/crypto/mq/sbox.py index 04246f9f339..c668832166f 100644 --- a/src/sage/crypto/mq/sbox.py +++ b/src/sage/crypto/mq/sbox.py @@ -334,9 +334,9 @@ def __call__(self, X): pass if len(str(X)) > 50: - raise TypeError, "Cannot apply SBox to provided element." + raise TypeError("Cannot apply SBox to provided element.") else: - raise TypeError, "Cannot apply SBox to %s."%(X,) + raise TypeError("Cannot apply SBox to %s."%(X,)) def __getitem__(self, X): """ @@ -779,7 +779,7 @@ def interpolation_polynomial(self, k=None): (a^2 + 1, 5) """ if self.m != self.n: - raise TypeError, "Lagrange interpolation only supported if self.m == self.n." + raise TypeError("Lagrange interpolation only supported if self.m == self.n.") if k is None: k = GF(2**self.m,'a') diff --git a/src/sage/crypto/mq/sr.py b/src/sage/crypto/mq/sr.py index dfac47e0dfb..064bd202ab6 100644 --- a/src/sage/crypto/mq/sr.py +++ b/src/sage/crypto/mq/sr.py @@ -438,19 +438,19 @@ def __init__(self, n=1, r=1, c=1, e=4, star=False, **kwargs): 1 8 3 3 """ if n-1 not in range(10): - raise TypeError, "n must be between 1 and 10 (inclusive)" + raise TypeError("n must be between 1 and 10 (inclusive)") self._n = n if r not in (1, 2, 4): - raise TypeError, "r must be in (1, 2, 4)" + raise TypeError("r must be in (1, 2, 4)") self._r = r if c not in (1, 2, 4): - raise TypeError, "c must be in (1, 2, 4)" + raise TypeError("c must be in (1, 2, 4)") self._c = c if e not in (4, 8): - raise TypeError, "e must be either 4 or 8" + raise TypeError("e must be either 4 or 8") self._e = e self._star = bool(star) @@ -586,7 +586,7 @@ def __getattr__(self, attr): self.Mstar = self.ShiftRows * self.Lin return self.Mstar - raise AttributeError, "%s has no attribute %s"%(type(self), attr) + raise AttributeError("%s has no attribute %s"%(type(self), attr)) def _repr_(self): """ @@ -711,7 +711,7 @@ def sub_byte(self, b): """ if not b: if not self._allow_zero_inversions: - raise ZeroDivisionError, "A zero inversion occurred during an encryption or key schedule." + raise ZeroDivisionError("A zero inversion occurred during an encryption or key schedule.") else: return self.sbox_constant() try: @@ -770,7 +770,7 @@ def sbox_constant(self): elif self.e == 8: return k.fetch_int(99) else: - raise TypeError, "sbox constant only defined for e in (4, 8)" + raise TypeError("sbox constant only defined for e in (4, 8)") def sbox(self, inversion_only=False): r""" @@ -1129,7 +1129,7 @@ def random_element(self, elem_type = "vector", *args, **kwds): elif elem_type == "state_array": return self.random_state_array(*args, **kwds) else: - raise TypeError, "parameter type not understood" + raise TypeError("parameter type not understood") def key_schedule(self, kj, i): """ @@ -1149,7 +1149,7 @@ def key_schedule(self, kj, i): CB 11 CF 8E """ if i < 0: - raise TypeError, "i must be >= i" + raise TypeError("i must be >= i") if i == 0: return kj @@ -1318,9 +1318,9 @@ def __call__(self, P, K): elif len(P) == len(K) == r*c*e: _type = self.vector else: - raise TypeError, "length %d or %d doesn't match either %d or %d"%(len(P),len(K),r*c,r*c*e) + raise TypeError("length %d or %d doesn't match either %d or %d"%(len(P),len(K),r*c,r*c*e)) else: - raise TypeError, "plaintext or key parameter not understood" + raise TypeError("plaintext or key parameter not understood") P = self.state_array(P) K = self.state_array(K) @@ -1409,7 +1409,7 @@ def hex_str(self, M, typ="matrix"): elif typ == "vector": return self.hex_str_vector(M) else: - raise TypeError, "parameter type must either be 'matrix' or 'vector'" + raise TypeError("parameter type must either be 'matrix' or 'vector'") def hex_str_matrix(self, M): r""" @@ -1912,7 +1912,7 @@ def key_schedule_polynomials(self, i): a = k.gen() if i < 0: - raise TypeError, "i must by >= 0" + raise TypeError("i must by >= 0") if i == 0: return tuple(self.field_polynomials("k", i, r*c)) @@ -2079,19 +2079,19 @@ def polynomial_system(self, P=None, K=None, C=None): plaintext, key, ciphertext = data if plaintext is False: - raise TypeError, "type %s of P not understood"%(type(plaintext)) + raise TypeError("type %s of P not understood"%(type(plaintext))) elif plaintext is None: plaintext = self.random_element("vector") if key is None: key = self.random_element("vector") elif key is False and ciphertext is False: - raise TypeError, "type %s of K not understood"%(type(key)) + raise TypeError("type %s of K not understood"%(type(key))) if ciphertext is None: ciphertext = self(plaintext, key) elif ciphertext is False: - raise TypeError, "type %s of C not understood"%(type(ciphertext)) + raise TypeError("type %s of C not understood"%(type(ciphertext))) for i in range(n+1): system.append( self.round_polynomials(i, plaintext, ciphertext) ) @@ -2903,7 +2903,7 @@ def inversion_polynomials_single_sbox(self, x=None, w=None, biaffine_only=None, elif is_Matrix(x): P = x.base_ring() else: - raise TypeError, "x not understood" + raise TypeError("x not understood") if is_Matrix(x): x = x.column(0).list() @@ -3078,7 +3078,7 @@ def _inversion_polynomials_single_sbox(self, x= None, w=None, biaffine_only=None elif is_Matrix(x): P = x.base_ring() else: - raise TypeError, "x not understood" + raise TypeError("x not understood") if isinstance(x, (tuple, list)): x = Matrix(P, e, 1, x) diff --git a/src/sage/crypto/stream.py b/src/sage/crypto/stream.py index 05fe000578a..2be8a726d76 100644 --- a/src/sage/crypto/stream.py +++ b/src/sage/crypto/stream.py @@ -55,7 +55,7 @@ def __init__(self, field = None): if field is None: field = FiniteField(2) if field.cardinality() != 2: - raise NotImplementedError, "Not yet implemented." + raise NotImplementedError("Not yet implemented.") S = BinaryStrings() P = PolynomialRing(FiniteField(2),'x') SymmetricKeyCryptosystem.__init__(self, S, S, None) @@ -71,15 +71,14 @@ def __call__(self, key): INPUT: A polynomial and initial state of the LFSR. """ if not isinstance(key, (list,tuple)) and len(key) == 2: - raise TypeError, "Argument key (= %s) must be a list of tuple of length 2" % key + raise TypeError("Argument key (= %s) must be a list of tuple of length 2" % key) poly = key[0]; IS = key[1] if not is_Polynomial(poly): - raise TypeError, "poly (= %s) must be a polynomial." % poly + raise TypeError("poly (= %s) must be a polynomial." % poly) if not isinstance(IS, (list,tuple)): - raise TypeError, "IS (= %s) must be an initial in the key space."%K + raise TypeError("IS (= %s) must be an initial in the key space."%K) if len(IS) != poly.degree(): - raise TypeError, \ - "The length of IS (= %s) must equal the degree of poly (= %s)" % (IS, poly) + raise TypeError("The length of IS (= %s) must equal the degree of poly (= %s)" % (IS, poly)) return LFSRCipher(self, poly, IS) def _repr_(self): @@ -98,7 +97,7 @@ def encoding(self,M): try: return S.encoding(M) except Exception: - raise TypeError, "Argument M = %s does not encode in the cipher domain" % M + raise TypeError("Argument M = %s does not encode in the cipher domain" % M) class ShrinkingGeneratorCryptosystem(SymmetricKeyCryptosystem): """ @@ -121,7 +120,7 @@ def __init__(self, field = None): if field is None: field = FiniteField(2) if field.cardinality() != 2: - raise NotImplementedError, "Not yet implemented." + raise NotImplementedError("Not yet implemented.") S = BinaryStrings() P = PolynomialRing(field, 'x') SymmetricKeyCryptosystem.__init__(self, S, S, None) @@ -137,10 +136,10 @@ def __call__(self, key): and decimating cipher e2. """ if not isinstance(key, (list,tuple)) and len(key) == 2: - raise TypeError, "Argument key (= %s) must be a list of tuple of length 2" % key + raise TypeError("Argument key (= %s) must be a list of tuple of length 2" % key) e1 = key[0]; e2 = key[1] if not isinstance(e1, LFSRCipher) or not isinstance(e2, LFSRCipher): - raise TypeError, "The key (= (%s,%s)) must be a tuple of two LFSR ciphers." % key + raise TypeError("The key (= (%s,%s)) must be a tuple of two LFSR ciphers." % key) return ShrinkingGeneratorCipher(self, e1, e2) def _repr_(self): @@ -160,7 +159,7 @@ def encoding(self,M): try: return S.encoding(M) except Exception: - raise TypeError, "Argument M = %s does not encode in the cipher domain" % M + raise TypeError("Argument M = %s does not encode in the cipher domain" % M) def blum_blum_shub(length, seed=None, p=None, q=None, lbound=None, ubound=None, ntries=100): diff --git a/src/sage/crypto/stream_cipher.py b/src/sage/crypto/stream_cipher.py index a3d4f3fa010..5ed1a7c65e4 100644 --- a/src/sage/crypto/stream_cipher.py +++ b/src/sage/crypto/stream_cipher.py @@ -88,7 +88,7 @@ def __call__(self, M, mode = "ECB"): """ B = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == B: - raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M + raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) (poly, IS) = self.key() n = B.ngens() # two for binary strings N = len(M) @@ -176,9 +176,9 @@ def __init__(self, parent, e1, e2): Shrinking generator cipher on Free binary string monoid """ if not isinstance(e1, LFSRCipher): - raise TypeError, "Argument e1 (= %s) must be a LFSR cipher." % e1 + raise TypeError("Argument e1 (= %s) must be a LFSR cipher." % e1) if not isinstance(e2, LFSRCipher): - raise TypeError, "Argument e2 (= %s) must be a LFSR cipher." % e2 + raise TypeError("Argument e2 (= %s) must be a LFSR cipher." % e2) SymmetricKeyCipher.__init__(self, parent, key = (e1, e2)) def keystream_cipher(self): @@ -254,7 +254,7 @@ def __call__(self, M, mode = "ECB"): """ B = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == B: - raise TypeError, "Argument M (= %s) must be a string in the plaintext space." % M + raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) (e1, e2) = self.key() MStream = M._element_list g1 = e1.connection_polynomial() diff --git a/src/sage/databases/oeis.py b/src/sage/databases/oeis.py index e027b7ea674..99a3d56ab9f 100644 --- a/src/sage/databases/oeis.py +++ b/src/sage/databases/oeis.py @@ -186,7 +186,7 @@ def _fetch(url): f.close() return result except IOError as msg: - raise IOError, "%s\nError fetching %s." % (msg, url) + raise IOError("%s\nError fetching %s." % (msg, url)) def _urls(html_string): r""" diff --git a/src/sage/finance/easter.py b/src/sage/finance/easter.py index 1b6adebca1a..583ec2f354d 100644 --- a/src/sage/finance/easter.py +++ b/src/sage/finance/easter.py @@ -75,7 +75,7 @@ def easter(year, algorithm=EASTER_WESTERN): algorithm = int(algorithm) if not (1 <= algorithm <= 3): - raise ValueError, "invalid algorithm" + raise ValueError("invalid algorithm") # g - Golden year - 1 # c - Century diff --git a/src/sage/functions/bessel.py b/src/sage/functions/bessel.py index fc51800c48a..fe78e9e80d8 100644 --- a/src/sage/functions/bessel.py +++ b/src/sage/functions/bessel.py @@ -1187,7 +1187,7 @@ def _bessel_I(nu,z,algorithm = "pari",prec=53): return K(pari(nu).besseli(z, precision=prec)) elif algorithm=="scipy": if prec != 53: - raise ValueError, "for the scipy algorithm the precision must be 53" + raise ValueError("for the scipy algorithm the precision must be 53") import scipy.special ans = str(scipy.special.iv(float(nu),complex(real(z),imag(z)))) ans = ans.replace("(","") @@ -1197,10 +1197,10 @@ def _bessel_I(nu,z,algorithm = "pari",prec=53): return real(ans) if z in RR else ans # Return real value when arg is real elif algorithm == "maxima": if prec != 53: - raise ValueError, "for the maxima algorithm the precision must be 53" + raise ValueError("for the maxima algorithm the precision must be 53") return sage_eval(maxima.eval("bessel_i(%s,%s)"%(float(nu),float(z)))) else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) def _bessel_J(nu,z,algorithm="pari",prec=53): r""" @@ -1281,7 +1281,7 @@ def _bessel_J(nu,z,algorithm="pari",prec=53): return K(pari(nu).besselj(z, precision=prec)) elif algorithm=="scipy": if prec != 53: - raise ValueError, "for the scipy algorithm the precision must be 53" + raise ValueError("for the scipy algorithm the precision must be 53") import scipy.special ans = str(scipy.special.jv(float(nu),complex(real(z),imag(z)))) ans = ans.replace("(","") @@ -1291,11 +1291,11 @@ def _bessel_J(nu,z,algorithm="pari",prec=53): return real(ans) if z in RR else ans elif algorithm == "maxima": if prec != 53: - raise ValueError, "for the maxima algorithm the precision must be 53" + raise ValueError("for the maxima algorithm the precision must be 53") f = maxima.function('n,z', 'bessel_j(n, z)') return f(nu, z) else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) def _bessel_K(nu,z,algorithm="pari",prec=53): r""" @@ -1341,7 +1341,7 @@ def _bessel_K(nu,z,algorithm="pari",prec=53): """ if algorithm=="scipy": if prec != 53: - raise ValueError, "for the scipy algorithm the precision must be 53" + raise ValueError("for the scipy algorithm the precision must be 53") import scipy.special ans = str(scipy.special.kv(float(nu),float(z))) ans = ans.replace("(","") @@ -1363,9 +1363,9 @@ def _bessel_K(nu,z,algorithm="pari",prec=53): K = z.parent() return K(pari(nu).besselk(z, precision=prec)) elif algorithm == 'maxima': - raise NotImplementedError, "The K-Bessel function is only implemented for the pari and scipy algorithms" + raise NotImplementedError("The K-Bessel function is only implemented for the pari and scipy algorithms") else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) def _bessel_Y(nu,z,algorithm="maxima", prec=53): @@ -1408,7 +1408,7 @@ def _bessel_Y(nu,z,algorithm="maxima", prec=53): """ if algorithm=="scipy": if prec != 53: - raise ValueError, "for the scipy algorithm the precision must be 53" + raise ValueError("for the scipy algorithm the precision must be 53") import scipy.special ans = str(scipy.special.yv(float(nu),complex(real(z),imag(z)))) ans = ans.replace("(","") @@ -1418,12 +1418,12 @@ def _bessel_Y(nu,z,algorithm="maxima", prec=53): return real(ans) if z in RR else ans elif algorithm == "maxima": if prec != 53: - raise ValueError, "for the maxima algorithm the precision must be 53" + raise ValueError("for the maxima algorithm the precision must be 53") return RR(maxima.eval("bessel_y(%s,%s)"%(float(nu),float(z)))) elif algorithm == "pari": - raise NotImplementedError, "The Y-Bessel function is only implemented for the maxima and scipy algorithms" + raise NotImplementedError("The Y-Bessel function is only implemented for the maxima and scipy algorithms") else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) class _Bessel(): """ @@ -1503,7 +1503,7 @@ def __init__(self, nu, typ = "J", algorithm = None, prec = 53): ValueError: typ must be one of I, J, K, Y """ if not (typ in ['I', 'J', 'K', 'Y']): - raise ValueError, "typ must be one of I, J, K, Y" + raise ValueError("typ must be one of I, J, K, Y") # Did the user ask for the default algorithm? if algorithm is None: @@ -1517,7 +1517,7 @@ def __init__(self, nu, typ = "J", algorithm = None, prec = 53): self._type = typ prec = int(prec) if prec < 0: - raise ValueError, "prec must be a positive integer" + raise ValueError("prec must be a positive integer") self._prec = int(prec) def __str__(self): diff --git a/src/sage/functions/other.py b/src/sage/functions/other.py index 8acaa5c5a05..53c36fede90 100644 --- a/src/sage/functions/other.py +++ b/src/sage/functions/other.py @@ -433,7 +433,7 @@ def __call__(self, x, maximum_bits=20000): return ceil(SR(x).full_simplify().simplify_radical()) except ValueError: pass - raise ValueError, "x (= %s) requires more than %s bits of precision to compute its ceiling"%(x, maximum_bits) + raise ValueError("x (= %s) requires more than %s bits of precision to compute its ceiling"%(x, maximum_bits)) except TypeError: # If x cannot be coerced into a RealField, then @@ -594,7 +594,7 @@ def __call__(self, x, maximum_bits=20000): return floor(SR(x).full_simplify().simplify_radical()) except ValueError: pass - raise ValueError, "x (= %s) requires more than %s bits of precision to compute its floor"%(x, maximum_bits) + raise ValueError("x (= %s) requires more than %s bits of precision to compute its floor"%(x, maximum_bits)) except TypeError: # If x cannot be coerced into a RealField, then @@ -1051,7 +1051,7 @@ def gamma(a, *args, **kwds): if not args: return gamma1(a, **kwds) if len(args) > 1: - raise TypeError, "Symbolic function gamma takes at most 2 arguments (%s given)"%(len(args)+1) + raise TypeError("Symbolic function gamma takes at most 2 arguments (%s given)"%(len(args)+1)) return incomplete_gamma(a,args[0],**kwds) # We have to add the wrapper function manually to the symbol_table when we have @@ -1211,7 +1211,7 @@ def psi(x, *args, **kwds): if not args: return psi1(x, **kwds) if len(args) > 1: - raise TypeError, "Symbolic function psi takes at most 2 arguments (%s given)"%(len(args)+1) + raise TypeError("Symbolic function psi takes at most 2 arguments (%s given)"%(len(args)+1)) return psi2(x,args[0],**kwds) # We have to add the wrapper function manually to the symbol_table when we have diff --git a/src/sage/functions/piecewise.py b/src/sage/functions/piecewise.py index 25decb7a651..25edebb9465 100644 --- a/src/sage/functions/piecewise.py +++ b/src/sage/functions/piecewise.py @@ -403,7 +403,7 @@ def riemann_sum_integral_approximation(self,N,mode=None): elif mode == "midpoint": return self._riemann_sum_helper(N, lambda x0, x1: (x1-x0)*self((x0+x1)/2)) else: - raise ValueError, "invalid mode" + raise ValueError("invalid mode") def riemann_sum(self,N,mode=None): """ @@ -452,7 +452,7 @@ def riemann_sum(self,N,mode=None): rsum = self._riemann_sum_helper(N, lambda x0,x1: [[(x0,x1),SR(self((x0+x1)/2))]], initial=[]) else: - raise ValueError, "invalid mode" + raise ValueError("invalid mode") return Piecewise(rsum) def trapezoid(self,N): @@ -666,7 +666,7 @@ def __call__(self,x0): for i in range(n): if endpts[i] < x0 < endpts[i+1]: return self.functions()[i](x0) - raise ValueError,"Value not defined outside of domain." + raise ValueError("Value not defined outside of domain.") def which_function(self,x0): """ @@ -685,7 +685,7 @@ def which_function(self,x0): for (a,b), f in self.list(): if a <= x0 <= b: return f - raise ValueError,"Function not defined outside of domain." + raise ValueError("Function not defined outside of domain.") def default_variable(self): r""" @@ -833,7 +833,7 @@ def integral(self, x=None, a=None, b=None, definite=False): return F(b) - F(a) if a != None or b != None: - raise TypeError, 'only one endpoint given' + raise TypeError('only one endpoint given') area = 0 # cumulative definite integral of parts to the left of the current interval integrand_pieces = self.list() diff --git a/src/sage/functions/special.py b/src/sage/functions/special.py index c716a8051f0..b348a3a7286 100644 --- a/src/sage/functions/special.py +++ b/src/sage/functions/special.py @@ -473,7 +473,7 @@ def _evalf_(self, *args, **kwds): """ parent = kwds['parent'] if hasattr(parent, 'prec') and parent.prec() > 53: - raise NotImplementedError, "%s not implemented for precision > 53"%self.name() + raise NotImplementedError("%s not implemented for precision > 53"%self.name()) _init() return parent(maxima("%s, numer"%self._maxima_init_evaled_(*args))) @@ -652,7 +652,7 @@ def hypergeometric_U(alpha,beta,x,algorithm="pari",prec=53): """ if algorithm=="scipy": if prec != 53: - raise ValueError, "for the scipy algorithm the precision must be 53" + raise ValueError("for the scipy algorithm the precision must be 53") import scipy.special ans = str(scipy.special.hyperu(float(alpha),float(beta),float(x))) ans = ans.replace("(","") @@ -664,7 +664,7 @@ def hypergeometric_U(alpha,beta,x,algorithm="pari",prec=53): R = RealField(prec) return R(pari(R(alpha)).hyperu(R(beta), R(x), precision=prec)) else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) def spherical_bessel_J(n, var, algorithm="maxima"): r""" @@ -689,7 +689,7 @@ def spherical_bessel_J(n, var, algorithm="maxima"): _init() return meval("spherical_bessel_j(%s,%s)"%(ZZ(n),var)) else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) def spherical_bessel_Y(n,var, algorithm="maxima"): r""" @@ -715,7 +715,7 @@ def spherical_bessel_Y(n,var, algorithm="maxima"): _init() return meval("spherical_bessel_y(%s,%s)"%(ZZ(n),var)) else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) def spherical_hankel1(n, var): r""" @@ -804,7 +804,7 @@ def elliptic_j(z): try: z = CC(z) except ValueError: - raise ValueError, "elliptic_j only defined for complex arguments." + raise ValueError("elliptic_j only defined for complex arguments.") from sage.libs.all import pari return CC(pari(z).ellj()) diff --git a/src/sage/games/hexad.py b/src/sage/games/hexad.py index 06f94c323f9..a054d7f8110 100644 --- a/src/sage/games/hexad.py +++ b/src/sage/games/hexad.py @@ -154,7 +154,7 @@ def __init__(self, type="shuffle"): elif type == "modulo11": self.minimog = minimog_modulo11 else: - raise ValueError, "That Minimog type is not implemented." + raise ValueError("That Minimog type is not implemented.") # This initializes the variables in the game. MS34 = MatrixSpace(SR,3,4) A = self.minimog diff --git a/src/sage/games/quantumino.py b/src/sage/games/quantumino.py index a6479a111b9..812529b5846 100644 --- a/src/sage/games/quantumino.py +++ b/src/sage/games/quantumino.py @@ -404,7 +404,7 @@ def __init__(self, aside, box=(5,8,2)): Aside pentamino number: 9 """ if not 0 <= aside < 17: - raise ValueError, "aside (=%s) must be between 0 and 16" % aside + raise ValueError("aside (=%s) must be between 0 and 16" % aside) self._aside = aside self._box = box diff --git a/src/sage/geometry/lattice_polytope.py b/src/sage/geometry/lattice_polytope.py index 41d18925993..235b477df60 100644 --- a/src/sage/geometry/lattice_polytope.py +++ b/src/sage/geometry/lattice_polytope.py @@ -337,14 +337,14 @@ def ReflexivePolytope(dim, n): """ if dim == 2: if n > 15: - raise ValueError, "there are only 16 reflexive polygons!" + raise ValueError("there are only 16 reflexive polygons!") return ReflexivePolytopes(2)[n] elif dim == 3: if n > 4318: - raise ValueError, "there are only 4319 reflexive 3-polytopes!" + raise ValueError("there are only 4319 reflexive 3-polytopes!") return ReflexivePolytopes(3)[n] else: - raise NotImplementedError, "only 2- and 3-dimensional reflexive polytopes are available!" + raise NotImplementedError("only 2- and 3-dimensional reflexive polytopes are available!") # Sequences of reflexive polytopes _rp = [None]*4 @@ -378,7 +378,7 @@ def ReflexivePolytopes(dim): """ global _rp if dim not in [2, 3]: - raise NotImplementedError, "only 2- and 3-dimensional reflexive polytopes are available!" + raise NotImplementedError("only 2- and 3-dimensional reflexive polytopes are available!") if _rp[dim] == None: rp = read_all_polytopes( os.path.join(data_location,"reflexive_polytopes_%dd"%dim), @@ -472,8 +472,7 @@ def __init__(self, data, desc, compute_vertices, copy_vertices=True, n=0): self.__init__(f, desc, compute_vertices) f.close() else: - raise TypeError, \ - "Cannot make a polytope from given data!\nData:\n%s" % data + raise TypeError("Cannot make a polytope from given data!\nData:\n%s" % data) def __eq__(self, other): r""" @@ -739,7 +738,7 @@ def _compute_hodge_numbers(self): ... NotImplementedError: use nef_partitions(hodge_numbers=True)! """ - raise NotImplementedError, "use nef_partitions(hodge_numbers=True)!" + raise NotImplementedError("use nef_partitions(hodge_numbers=True)!") def _copy_faces(self, other, reverse=False): r""" @@ -983,8 +982,8 @@ def _palp(self, command, reduce_dimension=False): 'M:5 4 F:4\n' """ if self.dim() <= 0: - raise ValueError, ("Cannot run \"%s\" for the zero-dimensional " - + "polytope!\nPolytope: %s") % (command, self) + raise ValueError(("Cannot run \"%s\" for the zero-dimensional " + + "polytope!\nPolytope: %s") % (command, self)) if self.dim() < self.ambient_dim() and not reduce_dimension: raise ValueError(("Cannot run PALP for a %d-dimensional polytope " + "in a %d-dimensional space!") % (self.dim(), self.ambient_dim())) @@ -1009,9 +1008,9 @@ def _palp(self, command, reduce_dimension=False): stdin.close() err = stderr.read() if len(err) > 0: - raise RuntimeError, ("Error executing \"%s\" for the given polytope!" + raise RuntimeError(("Error executing \"%s\" for the given polytope!" + "\nPolytope: %s\nVertices:\n%s\nOutput:\n%s") % (command, - self, self.vertices(), err) + self, self.vertices(), err)) result = stdout.read() # We program around an issue with subprocess (this so far seems to # only be an issue on Cygwin). @@ -1024,9 +1023,9 @@ def _palp(self, command, reduce_dimension=False): "failed." in result or "increase" in result or "Unable" in result): - raise ValueError, ("Error executing \"%s\" for the given polytope!" + raise ValueError(("Error executing \"%s\" for the given polytope!" + "\nPolytope: %s\nVertices:\n%s\nOutput:\n%s") % (command, - self, self.vertices(), result) + self, self.vertices(), result)) return result def _pullback(self, data): @@ -1209,7 +1208,7 @@ def _read_faces(self, data): return try: if self._constructed_as_polar: - raise ValueError, ("Cannot read face structure for a polytope " + raise ValueError("Cannot read face structure for a polytope " + "constructed as polar, use _compute_faces!") except AttributeError: pass @@ -1294,7 +1293,7 @@ def _read_nef_partitions(self, data): partitions[i] = [trans[v] for v in p] line = data.readline() if line == "": - raise ValueError, "more data expected!" + raise ValueError("more data expected!") partitions = Sequence([], cr=True) while len(line) > 0 and line.find("np=") == -1: if line.find("V:") == -1: @@ -1320,7 +1319,7 @@ def _read_nef_partitions(self, data): line = data.readline() start = line.find("np=") if start == -1: - raise ValueError, """Wrong data format, cannot find "np="!""" + raise ValueError("""Wrong data format, cannot find "np="!""") # The following block seems to be unnecessary (and requires taking into # account projections/products) # # Compare the number of found partitions with statistic. @@ -1628,7 +1627,7 @@ def faces(self, dim=None, codim=None): elif dim == None and codim != None: return self._faces[self.dim()-codim] else: - raise ValueError, "Both dim and codim are given!" + raise ValueError("Both dim and codim are given!") except AttributeError: self._compute_faces() return self.faces(dim, codim) @@ -1877,10 +1876,10 @@ def index(self): """ if not hasattr(self, "_index"): if not self.is_reflexive(): - raise NotImplementedError, "only reflexive polytopes can be indexed!" + raise NotImplementedError("only reflexive polytopes can be indexed!") dim = self.dim() if dim not in [2, 3]: - raise NotImplementedError, "only 2- and 3-dimensional polytopes can be indexed!" + raise NotImplementedError("only 2- and 3-dimensional polytopes can be indexed!") if LatticePolytopeClass._rp_dict[dim] == None: rp_dict = dict() for n, p in enumerate(ReflexivePolytopes(dim)): @@ -2060,8 +2059,8 @@ def nef_partitions(self, keep_symmetric=False, keep_products=True, Polytope: A lattice polytope: 3-dimensional, 6 vertices. """ if not self.is_reflexive(): - raise ValueError, ("The given polytope is not reflexive!\n" - + "Polytope: %s") % self + raise ValueError(("The given polytope is not reflexive!\n" + + "Polytope: %s") % self) keys = "-N -V" if keep_symmetric: keys += " -s" @@ -2390,7 +2389,7 @@ def plot3d(self, dim = self.dim() amb_dim = self.ambient_dim() if dim > 3: - raise ValueError, "%d-dimensional polytopes can not be plotted in 3D!" % self.dim() + raise ValueError("%d-dimensional polytopes can not be plotted in 3D!" % self.dim()) elif amb_dim > 3: return self._sublattice_polytope.plot3d( show_facets, facet_opacity, facet_color, @@ -2492,13 +2491,13 @@ def point(self, i): """ # Extra checks are made to compensate for a bug in Sage - column accepts any number. if i < 0: - raise ValueError, "polytopes don't have negative points!" + raise ValueError("polytopes don't have negative points!") elif i < self.nvertices(): return self.vertex(i) elif i < self.npoints(): return self.points().column(i, from_list=True) else: - raise ValueError, "the polytope does not have %d points!" % (i+1) + raise ValueError("the polytope does not have %d points!" % (i+1)) def points(self): r""" @@ -2581,8 +2580,8 @@ def polar(self): if self.is_reflexive(): return self._polar else: - raise ValueError, ("The given polytope is not reflexive!\n" - + "Polytope: %s") % self + raise ValueError(("The given polytope is not reflexive!\n" + + "Polytope: %s") % self) def poly_x(self, keys, reduce_dimension=False): r""" @@ -2786,7 +2785,7 @@ def traverse_boundary(self): [0, 1, 3, 2] """ if self.dim() != 2: - raise ValueError, "Boundary can be traversed only for 2-polytopes!" + raise ValueError("Boundary can be traversed only for 2-polytopes!") edges = self.edges() l = [0] for e in edges: @@ -2820,9 +2819,9 @@ def vertex(self, i): """ # The check is added to compensate for a bug in Sage - column works for any numbers if i < 0: - raise ValueError, "polytopes don't have negative vertices!" + raise ValueError("polytopes don't have negative vertices!") elif i > self.nvertices(): - raise ValueError, "the polytope does not have %d vertices!" % (i+1) + raise ValueError("the polytope does not have %d vertices!" % (i+1)) else: return self._vertices.column(i, from_list=True) @@ -3881,7 +3880,7 @@ def ordered_points(self): [0, 15, 1] """ if len(self.vertices()) != 2: - raise ValueError, "Order of points is defined for edges only!" + raise ValueError("Order of points is defined for edges only!") pcol = self._polytope.points().columns(copy=False) start = pcol[self.vertices()[0]] end = pcol[self.vertices()[1]] @@ -3934,7 +3933,7 @@ def traverse_boundary(self): [0, 4, 6, 2] """ if self not in self._polytope.faces(dim=2): - raise ValueError, "Boundary can be traversed only for 2-faces!" + raise ValueError("Boundary can be traversed only for 2-faces!") edges = [e for e in self._polytope.edges() if e.vertices()[0] in self.vertices() and e.vertices()[1] in self.vertices()] start = self.vertices()[0] @@ -4059,8 +4058,8 @@ def _palp(command, polytopes, reduce_dimension=False): stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr) err = stderr.read() if len(err) > 0: - raise RuntimeError, ("Error executing \"%s\" for a polytope sequence!" - + "\nOutput:\n%s") % (command, err) + raise RuntimeError(("Error executing \"%s\" for a polytope sequence!" + + "\nOutput:\n%s") % (command, err)) os.remove(input_file_name) try: p.terminate() @@ -4101,7 +4100,7 @@ def _read_nef_x_partitions(data): return partitions line = data.readline() if line == "": - raise ValueError, "Empty file!" + raise ValueError("Empty file!") partitions = [] while len(line) > 0 and line.find("np=") == -1: if line.find("V:") == -1: @@ -4118,10 +4117,10 @@ def _read_nef_x_partitions(data): end = line.find(" ", start) np = int(line[start:end]) if False and np != len(partitions): - raise ValueError, ("Found %d partitions, expected %d!" % + raise ValueError("Found %d partitions, expected %d!" % (len(partitions), np)) else: - raise ValueError, "Wrong data format, cannot find \"np=\"!" + raise ValueError("Wrong data format, cannot find \"np=\"!") return partitions def _read_poly_x_incidences(data, dim): @@ -4160,7 +4159,7 @@ def _read_poly_x_incidences(data, dim): data.readline() lines = [data.readline().split() for i in range(dim)] if len(lines) != dim: - raise ValueError, "Not enough data!" + raise ValueError("Not enough data!") n = len(lines[0][1]) # Number of vertices or facets result = [] for line in lines: @@ -4308,7 +4307,7 @@ def all_nef_partitions(polytopes, keep_symmetric=False): result = open(result_name) for p in polytopes: if not p.is_reflexive(): - raise ValueError, "The given polytope is not reflexive!\nPolytope: %s" % p + raise ValueError("The given polytope is not reflexive!\nPolytope: %s" % p) p._read_nef_partitions(result) p._nef_partitions_s = keep_symmetric result.close() @@ -4340,7 +4339,7 @@ def all_points(polytopes): for p in polytopes: p._points = p._embed(read_palp_matrix(result)) if p._points.nrows() == 0: - raise RuntimeError, ("Cannot read points of a polytope!" + raise RuntimeError("Cannot read points of a polytope!" +"\nPolytope: %s" % p) result.close() os.remove(result_name) @@ -4697,7 +4696,7 @@ def positive_integer_relations(points): c = [0]*(n+i) + [1] + [0]*(n_nonpivots - i - 1) x = maxima.linear_program(a, b, c) if x.str() == r'?Problem\not\feasible\!': - raise ValueError, "cannot find required relations" + raise ValueError("cannot find required relations") x = x.sage()[0][:n] v = relations.linear_combination_of_rows(x) new_relations.append(v) @@ -4961,10 +4960,10 @@ def skip_palp_matrix(data, n=1): for i in range(n): line = data.readline() if line == "": - raise ValueError, "There are not enough data to skip!" + raise ValueError("There are not enough data to skip!") for j in range(int(line.split()[0])): if data.readline() == "": - raise ValueError, "There are not enough data to skip!" + raise ValueError("There are not enough data to skip!") def write_palp_matrix(m, ofile=None, comment="", format=None): diff --git a/src/sage/geometry/polyhedron/backend_cdd.py b/src/sage/geometry/polyhedron/backend_cdd.py index ec44cc7152f..1af7d4adef5 100644 --- a/src/sage/geometry/polyhedron/backend_cdd.py +++ b/src/sage/geometry/polyhedron/backend_cdd.py @@ -200,8 +200,8 @@ def _init_from_cdd_output(self, cdd_output_string): def expect_in_cddout(expected_string): l = cddout.pop(0).strip() if l!=expected_string: - raise ValueError, ('Error while parsing cdd output: expected "' - +expected_string+'" but got "'+l+'".\n' ) + raise ValueError('Error while parsing cdd output: expected "' + +expected_string+'" but got "'+l+'".\n') # nested function def cdd_linearities(): l = cddout[0].split() diff --git a/src/sage/geometry/polyhedron/base.py b/src/sage/geometry/polyhedron/base.py index e89657d30e5..4af02532e51 100644 --- a/src/sage/geometry/polyhedron/base.py +++ b/src/sage/geometry/polyhedron/base.py @@ -2247,7 +2247,7 @@ def triangulated_facial_incidences(self): print 'Failed for face: ' + str(a_face) print 'Attempted simplicial face: ' + str(t_face) print 'Attempted lifted vertices: ' + str(lifted_verts) - raise RuntimeError, "triangulation failed" + raise RuntimeError("triangulation failed") normal_fdir = temp_poly.ieqs()[t_face[0]][-1] if normal_fdir >= 0: t_fac_verts = [temp_poly.vertices()[i] for i in t_face[1]] @@ -3340,7 +3340,7 @@ def render_solid(self, **kwds): return proj.render_solid_3d(**kwds) if self.ambient_dim()==2: return proj.render_fill_2d(**kwds) - raise ValueError, "render_solid is only defined for 2 and 3 dimensional polyhedra." + raise ValueError("render_solid is only defined for 2 and 3 dimensional polyhedra.") def render_wireframe(self, **kwds): """ @@ -3359,7 +3359,7 @@ def render_wireframe(self, **kwds): return proj.render_wireframe_3d(**kwds) if self.ambient_dim()==2: return proj.render_outline_2d(**kwds) - raise ValueError, "render_wireframe is only defined for 2 and 3 dimensional polyhedra." + raise ValueError("render_wireframe is only defined for 2 and 3 dimensional polyhedra.") def schlegel_projection(self, projection_dir = None, height = 1.1): """ @@ -3802,15 +3802,15 @@ def lattice_polytope(self, envelope=False): [ 0 -1 1 0 1] """ if not self.is_compact(): - raise NotImplementedError, 'Only compact lattice polytopes are allowed.' + raise NotImplementedError('Only compact lattice polytopes are allowed.') try: vertices = self.vertices_matrix(ZZ) except TypeError: if envelope==False: - raise ValueError, 'Some vertices are not integral. '+\ + raise ValueError('Some vertices are not integral. '+\ 'You probably want to add the argument '+\ - '"envelope=True" to compute an enveloping lattice polytope.' + '"envelope=True" to compute an enveloping lattice polytope.') vertices = [] for v in self.vertex_generator(): vbox = [ set([floor(x),ceil(x)]) for x in v ] @@ -3843,7 +3843,7 @@ def _integral_points_PALP(self): [(0, 1), (1, 0), (1, 1), (0, 0)] """ if not self.is_compact(): - raise ValueError, 'Can only enumerate points in a compact polyhedron.' + raise ValueError('Can only enumerate points in a compact polyhedron.') lp = self.lattice_polytope(True) # remove cached values to get accurate timings try: diff --git a/src/sage/geometry/polyhedron/library.py b/src/sage/geometry/polyhedron/library.py index c9f19ae2d2b..6c73f8509d4 100644 --- a/src/sage/geometry/polyhedron/library.py +++ b/src/sage/geometry/polyhedron/library.py @@ -227,7 +227,7 @@ def icosahedron(self, base_ring=QQ): g = RDF( (1 + sqrt(5))/2 ) r12 = RDF( QQ(1)/2 ) else: - raise ValueError, "field must be QQ or RDF." + raise ValueError("field must be QQ or RDF.") verts = [i([0,r12,g/2]) for i in AlternatingGroup(3)] verts = verts + [i([0,r12,-g/2]) for i in AlternatingGroup(3)] verts = verts + [i([0,-r12,g/2]) for i in AlternatingGroup(3)] diff --git a/src/sage/geometry/polyhedron/misc.py b/src/sage/geometry/polyhedron/misc.py index 7d2e6f96671..49794812c15 100644 --- a/src/sage/geometry/polyhedron/misc.py +++ b/src/sage/geometry/polyhedron/misc.py @@ -119,7 +119,7 @@ def _common_length_of(l1, l2=None, l3=None): num += 1 length_i = len(i) if length is not None and length_i != length: - raise ValueError, "Argument lengths differ!" + raise ValueError("Argument lengths differ!") length = length_i return num, length diff --git a/src/sage/geometry/polyhedron/plot.py b/src/sage/geometry/polyhedron/plot.py index 655eb829bbf..60c0e053a08 100644 --- a/src/sage/geometry/polyhedron/plot.py +++ b/src/sage/geometry/polyhedron/plot.py @@ -319,7 +319,7 @@ def __init__(self, projection_point): pproj = vector(RDF,self.projection_point) self.psize = norm(pproj) if (self.psize).is_zero(): - raise ValueError, "projection direction must be a non-zero vector." + raise ValueError("projection direction must be a non-zero vector.") v = vector(RDF, [0.0]*(self.dim-1) + [self.psize]) - pproj polediff = matrix(RDF,v).transpose() denom = RDF((polediff.transpose()*polediff)[0][0]) @@ -363,8 +363,8 @@ def __call__(self, x): img = self.house * x denom = self.psize-img[self.dim-1] if denom.is_zero(): - raise ValueError, 'Point cannot coincide with ' \ - 'coordinate singularity at ' + repr(x) + raise ValueError('Point cannot coincide with ' \ + 'coordinate singularity at ' + repr(x)) return vector(RDF, [img[i]/denom for i in range(self.dim-1)]) @@ -394,7 +394,7 @@ def __init__(self, projection_direction, height = 1.1): """ self.projection_dir = vector(RDF, projection_direction) if norm(self.projection_dir).is_zero(): - raise ValueError, "projection direction must be a non-zero vector." + raise ValueError("projection direction must be a non-zero vector.") self.dim = self.projection_dir.degree() spcenter = height * self.projection_dir/norm(self.projection_dir) self.height = height @@ -422,13 +422,13 @@ def __call__(self, x): """ v = vector(RDF,x) if v.is_zero(): - raise ValueError, "The origin must not be a vertex." + raise ValueError("The origin must not be a vertex.") v = v/norm(v) # normalize vertices to unit sphere v = self.house*v # reflect so self.projection_dir is at "north pole" denom = self.height-v[self.dim-1] if denom.is_zero(): - raise ValueError, 'Point cannot coincide with ' \ - 'coordinate singularity at ' + repr(x) + raise ValueError('Point cannot coincide with ' \ + 'coordinate singularity at ' + repr(x)) return vector(RDF, [ v[i]/denom for i in range(self.dim-1) ]) diff --git a/src/sage/geometry/polyhedron/representation.py b/src/sage/geometry/polyhedron/representation.py index 457323f2675..09729c07dfa 100644 --- a/src/sage/geometry/polyhedron/representation.py +++ b/src/sage/geometry/polyhedron/representation.py @@ -336,8 +336,7 @@ def _set_data(self, polyhedron, data): """ assert polyhedron.parent() is self._polyhedron_parent if len(data) != self._vector.degree(): - raise ValueError, \ - 'H-representation data requires a list of length ambient_dim+1' + raise ValueError('H-representation data requires a list of length ambient_dim+1') for i in range(0, self._vector.degree()): self._vector.set(i, data[i]) @@ -852,8 +851,7 @@ def _set_data(self, polyhedron, data): """ assert polyhedron.parent() is self._polyhedron_parent if len(data) != self._vector.degree(): - raise ValueError, \ - 'V-representation data requires a list of length ambient_dim' + raise ValueError('V-representation data requires a list of length ambient_dim') for i in range(0, self._vector.degree()): self._vector.set(i, data[i]) diff --git a/src/sage/geometry/polytope.py b/src/sage/geometry/polytope.py index 40a8a346a4b..795ded7efcb 100644 --- a/src/sage/geometry/polytope.py +++ b/src/sage/geometry/polytope.py @@ -90,7 +90,7 @@ def _repr_(self): def __add__(self, other): if not isinstance(other, Polytope): - raise TypeError, "other (=%s) must be a polytope"%other + raise TypeError("other (=%s) must be a polytope"%other) output_file = tmp_filename() infile1 = tmp_filename() open(infile1,'w').write(self.__data) @@ -102,7 +102,7 @@ def __add__(self, other): stdin.close() err = stderr.read() if len(err) > 0: - raise RuntimeError, err + raise RuntimeError(err) print stdout.read(), err S = polymake.from_data(open(output_file).read()) os.unlink(infile1) @@ -138,10 +138,10 @@ def cmd(self, cmd): polymake_processes = Popen([polymake_command, F, cmd],stdout=PIPE,stderr=PIPE) ans, err = polymake_processes.communicate() if len(err) > 0: - raise RuntimeError, err + raise RuntimeError(err) if len(ans) == 0: - raise ValueError, "%s\nError executing polymake command %s"%( - err,cmd) + raise ValueError("%s\nError executing polymake command %s"%( + err,cmd)) self.__data = open(F).read() return ans @@ -260,7 +260,7 @@ def __make(self, cmd, name): try: d = open(tmp_file).read() except IOError: - raise RuntimeError, "You may need to install the polymake package" + raise RuntimeError("You may need to install the polymake package") return Polytope(d, name) def reconfigure(self): diff --git a/src/sage/geometry/toric_lattice.py b/src/sage/geometry/toric_lattice.py index 967c9a04824..d20c5d2fc01 100644 --- a/src/sage/geometry/toric_lattice.py +++ b/src/sage/geometry/toric_lattice.py @@ -1390,14 +1390,14 @@ def __init__(self, V, W, check=True, positive_point=None, positive_dual_point=No point_quotient = self(positive_point) scalar_product = quotient_generator.vector()[0] * point_quotient.vector()[0] if scalar_product==0: - raise ValueError, str(positive_point)+' is zero in the quotient.' + raise ValueError(str(positive_point)+' is zero in the quotient.') elif (positive_point==None) and (positive_dual_point!=None): assert positive_dual_point in lattice.dual(), 'positive_dual_point must be a dual lattice point.' scalar_product = quotient_generator.lift() * positive_dual_point if scalar_product==0: - raise ValueError, str(positive_dual_point)+' is zero on the lift of the quotient generator.' + raise ValueError(str(positive_dual_point)+' is zero on the lift of the quotient generator.') else: - raise ValueError, 'You may not specify both positive_point and positive_dual_point.' + raise ValueError('You may not specify both positive_point and positive_dual_point.') self._flip_sign_of_generator = (scalar_product<0) def gens(self): diff --git a/src/sage/geometry/triangulation/element.py b/src/sage/geometry/triangulation/element.py index d9442ca8637..5a4a5eb5eef 100644 --- a/src/sage/geometry/triangulation/element.py +++ b/src/sage/geometry/triangulation/element.py @@ -437,8 +437,7 @@ def plot(self, **kwds): if dim == 3: return triangulation_render_3d(self, **kwds) - raise NotImplementedError, \ - 'Plotting '+str(dim)+'-dimensional triangulations not implemented!' + raise NotImplementedError('Plotting '+str(dim)+'-dimensional triangulations not implemented!') def gkz_phi(self): diff --git a/src/sage/geometry/triangulation/point_configuration.py b/src/sage/geometry/triangulation/point_configuration.py index 4fc4479487b..587eae641e6 100644 --- a/src/sage/geometry/triangulation/point_configuration.py +++ b/src/sage/geometry/triangulation/point_configuration.py @@ -331,7 +331,7 @@ def __init__(self, points, connected, fine, regular, star, defined_affine): assert connected in [True, False], 'Unknown value: connected='+str(connected) self._connected = connected if connected!=True and not PointConfiguration._have_TOPCOM(): - raise ValueError, 'You must install TOPCOM to find non-connected triangulations.' + raise ValueError('You must install TOPCOM to find non-connected triangulations.') assert fine in [True, False], 'Unknown value: fine='+str(fine) self._fine = fine @@ -339,7 +339,7 @@ def __init__(self, points, connected, fine, regular, star, defined_affine): assert regular in [True, False, None], 'Unknown value: regular='+str(regular) self._regular = regular if regular!=None and not PointConfiguration._have_TOPCOM(): - raise ValueError, 'You must install TOPCOM to test for regularity.' + raise ValueError('You must install TOPCOM to test for regularity.') assert star==None or star in ZZ, 'Unknown value: fine='+str(star) self._star = star @@ -372,7 +372,7 @@ def set_engine(cls, engine='auto'): sage: p.set_engine('internal') # optional - TOPCOM """ if engine not in ['auto', 'TOPCOM', 'internal']: - raise ValueError, 'Unknown value for "engine": '+str(engine) + raise ValueError('Unknown value for "engine": '+str(engine)) have_TOPCOM = PointConfiguration._have_TOPCOM() PointConfiguration._use_TOPCOM = \ @@ -412,7 +412,7 @@ def star_center(self): ValueError: The point configuration has no star center defined. """ if self._star is None: - raise ValueError, 'The point configuration has no star center defined.' + raise ValueError('The point configuration has no star center defined.') else: return self[self._star] @@ -976,9 +976,9 @@ def triangulations(self, verbose=False): yield triangulation else: if (self._connected!=True): - raise ValueError, 'Need TOPCOM to find disconnected triangulations.' + raise ValueError('Need TOPCOM to find disconnected triangulations.') if (self._regular!=None): - raise ValueError, 'Need TOPCOM to test for regularity.' + raise ValueError('Need TOPCOM to test for regularity.') ci = ConnectedTriangulationsIterator(self, star=self._star, fine=self._fine) for encoded_triangulation in ci: yield self(encoded_triangulation) @@ -1061,7 +1061,7 @@ def triangulate(self, verbose=False): except StopIteration: # there is no triangulation pass - raise ValueError, 'No triangulation with the required properties.' + raise ValueError('No triangulation with the required properties.') def convex_hull(self): diff --git a/src/sage/graphs/digraph.py b/src/sage/graphs/digraph.py index 3d2dd9e4e85..c3846600bfb 100644 --- a/src/sage/graphs/digraph.py +++ b/src/sage/graphs/digraph.py @@ -1949,7 +1949,7 @@ def reverse_edge(self, u, v=None, label=None, inplace=True, multiedges=None): pass if not self.has_edge(u,v,label): - raise ValueError, "Input edge must exist in the digraph." + raise ValueError("Input edge must exist in the digraph.") tempG = self if inplace else self.copy() diff --git a/src/sage/graphs/digraph_generators.py b/src/sage/graphs/digraph_generators.py index dd4e8844ce2..d00636a3509 100644 --- a/src/sage/graphs/digraph_generators.py +++ b/src/sage/graphs/digraph_generators.py @@ -261,7 +261,7 @@ def ButterflyGraph(self, n, vertices='strings'): # We could switch to Sage integers to handle arbitrary n. if vertices=='strings': if n>=31: - raise NotImplementedError, "vertices='strings' is only valid for n<=30." + raise NotImplementedError("vertices='strings' is only valid for n<=30.") from sage.graphs.generic_graph_pyx import binary butterfly = {} for v in xrange(2**n): @@ -287,7 +287,7 @@ def ButterflyGraph(self, n, vertices='strings'): # a vector from the tuple t, just call vector(t). butterfly[(tuple(v),i)]=[(tuple(v),i+1), (tuple(w),i+1)] else: - raise NotImplementedError, "vertices must be 'strings' or 'vectors'." + raise NotImplementedError("vertices must be 'strings' or 'vectors'.") return DiGraph(butterfly) def Path(self,n): diff --git a/src/sage/graphs/generators/families.py b/src/sage/graphs/generators/families.py index 56c555f8912..189bf579aee 100644 --- a/src/sage/graphs/generators/families.py +++ b/src/sage/graphs/generators/families.py @@ -109,9 +109,9 @@ def KneserGraph(n,k): """ if not n>0: - raise ValueError, "Parameter n should be a strictly positive integer" + raise ValueError("Parameter n should be a strictly positive integer") if not (k>0 and k<=n): - raise ValueError, "Parameter k should be a strictly positive integer inferior to n" + raise ValueError("Parameter k should be a strictly positive integer inferior to n") g = Graph(name="Kneser graph with parameters "+str(n)+","+str(k)) from sage.combinat.subset import Subsets @@ -858,7 +858,7 @@ def FuzzyBallGraph(partition, q): """ from sage.graphs.generators.basic import CompleteGraph if len(partition)<1: - raise ValueError, "partition must be a nonempty list of positive integers" + raise ValueError("partition must be a nonempty list of positive integers") n=q+sum(partition) g=CompleteGraph(n) curr_vertex=0 @@ -1237,7 +1237,7 @@ def MycielskiGraph(k=1, relabel=True): g.name("Mycielski Graph " + str(k)) if k<0: - raise ValueError, "parameter k must be a nonnegative integer" + raise ValueError("parameter k must be a nonnegative integer") if k == 0: return g @@ -1441,7 +1441,7 @@ def OddGraph(n): """ if not n>1: - raise ValueError, "Parameter n should be an integer strictly greater than 1" + raise ValueError("Parameter n should be an integer strictly greater than 1") g = KneserGraph(2*n-1,n-1) g.name("Odd Graph with parameter %s" % n) return g diff --git a/src/sage/graphs/generators/random.py b/src/sage/graphs/generators/random.py index 4b74922178a..a07b97731f9 100644 --- a/src/sage/graphs/generators/random.py +++ b/src/sage/graphs/generators/random.py @@ -213,9 +213,9 @@ def RandomBipartite(n1,n2, p): complement(Random bipartite graph of size 5+6 with edge probability 0.200000000000000): Graph on 11 vertices """ if not (p>=0 and p<=1): - raise ValueError, "Parameter p is a probability, and so should be a real value between 0 and 1" + raise ValueError("Parameter p is a probability, and so should be a real value between 0 and 1") if not (n1>0 and n2>0): - raise ValueError, "n1 and n2 should be integers strictly greater than 0" + raise ValueError("n1 and n2 should be integers strictly greater than 0") from numpy.random import uniform diff --git a/src/sage/graphs/graph.py b/src/sage/graphs/graph.py index 2441de472be..a720614b714 100644 --- a/src/sage/graphs/graph.py +++ b/src/sage/graphs/graph.py @@ -2917,7 +2917,7 @@ def degree_constrained_subgraph(self, bounds=None, solver=None, verbose=0): reorder = lambda x,y: (x,y) if x 0 ): num_arrays += 1 diff --git a/src/sage/graphs/linearextensions.py b/src/sage/graphs/linearextensions.py index aff540431aa..df4d7691d58 100644 --- a/src/sage/graphs/linearextensions.py +++ b/src/sage/graphs/linearextensions.py @@ -266,7 +266,7 @@ def right(self, i, letter): return True return False else: - raise ValueError, "Bad letter!" + raise ValueError("Bad letter!") def generate_linear_extensions(self, i): """ diff --git a/src/sage/groups/abelian_gps/abelian_group.py b/src/sage/groups/abelian_gps/abelian_group.py index 204ad494fc0..8cac2242cee 100644 --- a/src/sage/groups/abelian_gps/abelian_group.py +++ b/src/sage/groups/abelian_gps/abelian_group.py @@ -902,7 +902,7 @@ def gen(self, i=0): """ n = self.ngens() if i < 0 or i >= n: - raise IndexError, "Argument i (= %s) must be between 0 and %s."%(i, n-1) + raise IndexError("Argument i (= %s) must be between 0 and %s."%(i, n-1)) x = [0]*n if self._gens_orders[i] != 1: x[i] = 1 @@ -1219,7 +1219,7 @@ def list(self): (1,) """ if not(self.is_finite()): - raise NotImplementedError, "Group must be finite" + raise NotImplementedError("Group must be finite") return tuple(self.__iter__()) def __iter__(self): @@ -1293,7 +1293,7 @@ def subgroups(self, check=False): sage: AbelianGroup([]).subgroups() [Trivial Abelian group] """ - if not self.is_finite(): raise ValueError, "Group must be finite" + if not self.is_finite(): raise ValueError("Group must be finite") from sage.misc.misc import verbose if self.is_trivial(): @@ -1329,7 +1329,7 @@ def subgroups(self, check=False): verbose("Running Gap cross-check") t = ZZ(gap.eval("Size(SubgroupsSolvableGroup(AbelianGroup(%s)))" % v)) if t != len(subgps): - raise ArithmeticError, "For %s Gap finds %s subgroups, I found %s" % (v, t, len(subgps)) + raise ArithmeticError("For %s Gap finds %s subgroups, I found %s" % (v, t, len(subgps))) verbose("Gap check OK for %s: %s" % (v, t)) return subgps @@ -1454,9 +1454,9 @@ def __init__(self, ambient, gens, names="f"): """ from sage.interfaces.all import gap if not isinstance(ambient, AbelianGroup_class): - raise TypeError, "ambient (=%s) must be an abelian group."%ambient + raise TypeError("ambient (=%s) must be an abelian group."%ambient) if not isinstance(gens, tuple): - raise TypeError, "gens (=%s) must be a tuple"%gens + raise TypeError("gens (=%s) must be a tuple"%gens) self._ambient_group = ambient Hgens = tuple(x for x in gens if x != ambient.one()) ## in case someone puts 1 in the list of generators diff --git a/src/sage/groups/abelian_gps/abelian_group_morphism.py b/src/sage/groups/abelian_gps/abelian_group_morphism.py index 504b1db2613..2663a7b98b7 100644 --- a/src/sage/groups/abelian_gps/abelian_group_morphism.py +++ b/src/sage/groups/abelian_gps/abelian_group_morphism.py @@ -103,16 +103,16 @@ def __init__(self, G, H, genss, imgss ): from sage.categories.homset import Hom Morphism.__init__(self, Hom(G, H)) if len(genss) != len(imgss): - raise TypeError, "Sorry, the lengths of %s, %s must be equal."%(genss,imgss) + raise TypeError("Sorry, the lengths of %s, %s must be equal."%(genss,imgss)) self._domain = G self._codomain = H if not(G.is_abelian()): - raise TypeError, "Sorry, the groups must be abelian groups." + raise TypeError("Sorry, the groups must be abelian groups.") if not(H.is_abelian()): - raise TypeError, "Sorry, the groups must be abelian groups." + raise TypeError("Sorry, the groups must be abelian groups.") G_domain = G.subgroup(genss) if G_domain.order() != G.order(): - raise TypeError, "Sorry, the list %s must generate G."%genss + raise TypeError("Sorry, the list %s must generate G."%genss) # self.domain_invs = G.gens_orders() # self.codomaininvs = H.gens_orders() self.domaingens = genss @@ -120,7 +120,7 @@ def __init__(self, G, H, genss, imgss ): #print genss, imgss for i in range(len(self.domaingens)): if (self.domaingens[i]).order() != (self.codomaingens[i]).order(): - raise TypeError, "Sorry, the orders of the corresponding elements in %s, %s must be equal."%(genss,imgss) + raise TypeError("Sorry, the orders of the corresponding elements in %s, %s must be equal."%(genss,imgss)) def _gap_init_(self): """ diff --git a/src/sage/groups/abelian_gps/dual_abelian_group.py b/src/sage/groups/abelian_gps/dual_abelian_group.py index 8253a281ac9..91f6cf62923 100644 --- a/src/sage/groups/abelian_gps/dual_abelian_group.py +++ b/src/sage/groups/abelian_gps/dual_abelian_group.py @@ -255,7 +255,7 @@ def gen(self, i=0): """ n = self.group().ngens() if i < 0 or i >= n: - raise IndexError, "Argument i (= %s) must be between 0 and %s."%(i, n-1) + raise IndexError("Argument i (= %s) must be between 0 and %s."%(i, n-1)) x = [0]*n if self.gens_orders()[i] != 1: x[i] = 1 @@ -381,7 +381,7 @@ def list(self): (1, B, B^2, A, A*B, A*B^2) """ if not(self.is_finite()): - raise NotImplementedError, "Group must be finite" + raise NotImplementedError("Group must be finite") invs = self.gens_orders() T = mrange(invs) n = self.order() diff --git a/src/sage/groups/additive_abelian/additive_abelian_group.py b/src/sage/groups/additive_abelian/additive_abelian_group.py index 5cdc575d13b..090f56f264c 100644 --- a/src/sage/groups/additive_abelian/additive_abelian_group.py +++ b/src/sage/groups/additive_abelian/additive_abelian_group.py @@ -108,7 +108,7 @@ def AdditiveAbelianGroup(invs, remember_generators = True): True """ invs = [ZZ(x) for x in invs] - if not all( [x >= 0 for x in invs] ): raise ValueError, "Invariants must be nonnegative" + if not all( [x >= 0 for x in invs] ): raise ValueError("Invariants must be nonnegative") A, B = cover_and_relations_from_invariants(invs) if remember_generators: G = AdditiveAbelianGroup_fixed_gens(A, B, A.gens()) diff --git a/src/sage/groups/additive_abelian/additive_abelian_wrapper.py b/src/sage/groups/additive_abelian/additive_abelian_wrapper.py index 887e39bffca..e6c5dd1976d 100644 --- a/src/sage/groups/additive_abelian/additive_abelian_wrapper.py +++ b/src/sage/groups/additive_abelian/additive_abelian_wrapper.py @@ -247,9 +247,9 @@ def _discrete_log(self,x): # EVEN DUMBER IMPLEMENTATION! from sage.rings.infinity import Infinity if self.order() == Infinity: - raise NotImplementedError, "No black-box discrete log for infinite abelian groups" + raise NotImplementedError("No black-box discrete log for infinite abelian groups") u = [y for y in self.list() if y.element() == x] - if len(u) == 0: raise TypeError, "Not in group" + if len(u) == 0: raise TypeError("Not in group") if len(u) > 1: raise NotImplementedError return u[0].vector() diff --git a/src/sage/groups/generic.py b/src/sage/groups/generic.py index c0f67c10506..ff20df881aa 100644 --- a/src/sage/groups/generic.py +++ b/src/sage/groups/generic.py @@ -176,7 +176,7 @@ def multiple(a, n, operation='*', identity=None, inverse=None, op=None): op = add else: if identity is None or inverse is None or op is None: - raise ValueError, "identity, inverse and operation must all be specified" + raise ValueError("identity, inverse and operation must all be specified") if n == 0: return identity @@ -308,7 +308,7 @@ def __init__(self,P,n,P0=None,indexed=False, operation='+', op=None): ``P0`` must be supplied. """ if n<0: - raise ValueError, 'n cannot be negative in multiples' + raise ValueError('n cannot be negative in multiples') from operator import mul, add @@ -321,9 +321,9 @@ def __init__(self,P,n,P0=None,indexed=False, operation='+', op=None): else: self.op = op if P0 is None: - raise ValueError, "P0 must be supplied when operation is neither addition nor multiplication" + raise ValueError("P0 must be supplied when operation is neither addition nor multiplication") if op is None: - raise ValueError, "op() must both be supplied when operation is neither addition nor multiplication" + raise ValueError("op() must both be supplied when operation is neither addition nor multiplication") self.P=copy(P) self.Q=copy(P0) @@ -446,14 +446,14 @@ def bsgs(a, b, bounds, operation='*', identity=None, inverse=None, op=None): op = add else: if identity is None or inverse is None or op is None: - raise ValueError, "identity, inverse and operation must be given" + raise ValueError("identity, inverse and operation must be given") lb, ub = bounds if lb<0 or ub= self.dimension(): - raise ValueError, "Can only compute the nth face if 0 <= n < dim." + raise ValueError("Can only compute the nth face if 0 <= n < dim.") idx = self.nondegenerate_intervals()[n] t = self.__tuple if upper: @@ -453,7 +453,7 @@ def _compare_for_gluing(self, other): """ d = self.dimension() if d != other.dimension(): - raise ValueError, "Cubes must be of the same dimension." + raise ValueError("Cubes must be of the same dimension.") insert_self = [] insert_other = [] translate = [] @@ -891,7 +891,7 @@ def cells(self, subcomplex=None): if subcomplex not in self._cells: if subcomplex is not None and subcomplex.dimension() > -1: if not subcomplex.is_subcomplex(self): - raise ValueError, "The 'subcomplex' is not actually a subcomplex." + raise ValueError("The 'subcomplex' is not actually a subcomplex.") # Cells is the dictionary of cells in self but not in # subcomplex, indexed by dimension Cells = {} @@ -1168,7 +1168,7 @@ def join(self, other): ... NotImplementedError: Joins are not implemented for cubical complexes. """ - raise NotImplementedError, "Joins are not implemented for cubical complexes." + raise NotImplementedError("Joins are not implemented for cubical complexes.") # Use * to mean 'join': # __mul__ = join @@ -1193,7 +1193,7 @@ def cone(self): NotImplementedError: Cones are not implemented for cubical complexes. """ #return self.join(cubical_complexes.Cube(0)) - raise NotImplementedError, "Cones are not implemented for cubical complexes." + raise NotImplementedError("Cones are not implemented for cubical complexes.") def suspension(self, n=1): r""" @@ -1224,7 +1224,7 @@ def suspension(self, n=1): # if n==1: # return self.join(cubical_complexes.Sphere(0)) # return self.suspension().suspension(int(n-1)) - raise NotImplementedError, "Suspensions are not implemented for cubical complexes." + raise NotImplementedError("Suspensions are not implemented for cubical complexes.") def product(self, other): r""" @@ -1347,7 +1347,7 @@ def connected_sum(self, other): # C x 0 and C x 1, putting in its place (its boundary) x (0,1). if not (self.is_pure() and other.is_pure() and self.dimension() == other.dimension()): - raise ValueError, "Complexes are not pure of the same dimension." + raise ValueError("Complexes are not pure of the same dimension.") self_facets = list(self.maximal_cells()) other_facets = list(other.maximal_cells()) diff --git a/src/sage/homology/delta_complex.py b/src/sage/homology/delta_complex.py index 2fe5d2ce348..4049fc6b631 100644 --- a/src/sage/homology/delta_complex.py +++ b/src/sage/homology/delta_complex.py @@ -307,7 +307,7 @@ def store_bdry(simplex, faces): new_data[dim] = [] for x in data: if not isinstance(x, Simplex): - raise TypeError, "Each key in the data dictionary must be a simplex." + raise TypeError("Each key in the data dictionary must be a simplex.") old_data_by_dim[x.dimension()].append(x) old_delayed = {} for dim in range(dimension, -1, -1): @@ -337,7 +337,7 @@ def store_bdry(simplex, faces): current[bdry] = store_bdry(bdry, bdry.faces()) new_data[dim].append(current[bdry]) else: - raise ValueError, "In the data dictionary, there is a value which is a simplex not already in the dictionary. This is not allowed." + raise ValueError("In the data dictionary, there is a value which is a simplex not already in the dictionary. This is not allowed.") elif isinstance(bdry, (list, tuple)): # case 2 # boundary is a list or tuple @@ -353,7 +353,7 @@ def store_bdry(simplex, faces): if dim > 0: old_data_by_dim[dim-1].extend(old_delayed.keys()) else: - raise ValueError, "data is not a list, tuple, or dictionary" + raise ValueError("data is not a list, tuple, or dictionary") for n in new_data: new_data[n] = tuple(new_data[n]) # at this point, new_data is a dictionary indexed by @@ -368,7 +368,7 @@ def store_bdry(simplex, faces): if not all(faces[s[j]][i] == faces[s[i]][j-1] for i in range(j)): msg = "Simplicial identity d_i d_j = d_{j-1} d_i fails" msg += " for j=%s, in dimension %s"%(j,d) - raise ValueError, msg + raise ValueError(msg) # self._cells_dict: dictionary indexed by dimension d: for # each d, have list or tuple of simplices, and for each # simplex, have list or tuple with its boundary (as the index @@ -528,7 +528,7 @@ def cells(self, subcomplex=None): cells[d] = [None]*l # get rid of all cells return cells else: - raise ValueError, "This is not a subcomplex of self." + raise ValueError("This is not a subcomplex of self.") else: subcomplex_cells = subcomplex._is_subcomplex_of[self] for d in range(0, max(subcomplex_cells.keys())+1): @@ -843,7 +843,7 @@ def suspension(self, n=1): {0: 0, 1: 0, 2: 0, 3: Z} """ if n<0: - raise ValueError, "n must be non-negative." + raise ValueError("n must be non-negative.") if n==0: return self if n==1: @@ -1078,7 +1078,7 @@ def connected_sum(self, other): Z x Z x C2 """ if not self.dimension() == other.dimension(): - raise ValueError, "Complexes are not of the same dimension." + raise ValueError("Complexes are not of the same dimension.") dim = self.dimension() # Look at the last simplex in the list of top-dimensional # simplices for each complex. If there are identifications on @@ -1412,7 +1412,7 @@ def barycentric_subdivision(self): ... NotImplementedError: Barycentric subdivisions are not implemented for Delta complexes. """ - raise NotImplementedError, "Barycentric subdivisions are not implemented for Delta complexes." + raise NotImplementedError("Barycentric subdivisions are not implemented for Delta complexes.") # the second barycentric subdivision is a simplicial complex. implement this somehow? # def simplicial_complex(self): diff --git a/src/sage/homology/examples.py b/src/sage/homology/examples.py index 2ffc1a5b1e5..ed7911e97c2 100644 --- a/src/sage/homology/examples.py +++ b/src/sage/homology/examples.py @@ -334,7 +334,7 @@ def SurfaceOfGenus(self, g, orientable=True): """ if g == 0: if not orientable: - raise ValueError, "No non-orientable surface of genus zero." + raise ValueError("No non-orientable surface of genus zero.") else: return simplicial_complexes.Sphere(2) if orientable: diff --git a/src/sage/homology/simplicial_complex_homset.py b/src/sage/homology/simplicial_complex_homset.py index f51fa027b26..56b86f42fe6 100644 --- a/src/sage/homology/simplicial_complex_homset.py +++ b/src/sage/homology/simplicial_complex_homset.py @@ -129,7 +129,7 @@ def diagonal_morphism(self,rename_vertices=True): f[i] = (i,i) return simplicial_complex_morphism.SimplicialComplexMorphism(f, self._domain,X) else: - raise TypeError, "Diagonal morphism is only defined for Hom(X,XxX)." + raise TypeError("Diagonal morphism is only defined for Hom(X,XxX).") def identity(self): """ @@ -178,7 +178,7 @@ def an_element(self): if len(X_vertices) == 0: return dict() else: - raise TypeError, "There are no morphisms from a non-empty simplicial complex to an empty simplicial comples." + raise TypeError("There are no morphisms from a non-empty simplicial complex to an empty simplicial comples.") f = dict() for x in X_vertices: f[x]=i diff --git a/src/sage/homology/simplicial_complex_morphism.py b/src/sage/homology/simplicial_complex_morphism.py index 2100c1fedf4..75b4d0172a2 100644 --- a/src/sage/homology/simplicial_complex_morphism.py +++ b/src/sage/homology/simplicial_complex_morphism.py @@ -229,7 +229,7 @@ def __call__(self,x,orientation=False): """ dim = self._domain.dimension() if not isinstance(x,simplicial_complex.Simplex) or x.dimension() > dim or not x in self._domain.faces()[x.dimension()]: - raise ValueError, "x must be a simplex of the source of f" + raise ValueError("x must be a simplex of the source of f") tup=x.tuple() fx=[] for j in tup: diff --git a/src/sage/interacts/debugger.py b/src/sage/interacts/debugger.py index db449f240a7..8e7145c17cf 100644 --- a/src/sage/interacts/debugger.py +++ b/src/sage/interacts/debugger.py @@ -78,7 +78,7 @@ def __init__(self): tb=tb.tb_next self._stack = inspect.getinnerframes(tb) except AttributeError: - raise RuntimeError, "no traceback has been produced; nothing to debug" + raise RuntimeError("no traceback has been produced; nothing to debug") self._curframe_index = len(self._stack) - 1 def curframe(self): diff --git a/src/sage/interacts/library.py b/src/sage/interacts/library.py index 1d1993a3a9a..eb88bc2e1ee 100644 --- a/src/sage/interacts/library.py +++ b/src/sage/interacts/library.py @@ -743,7 +743,7 @@ def _bisection_method(f, a, b, maxn, eps): elif fc*fb < 0: a, b = c, b else: - raise ValueError, "f must have a sign change in the interval (%s,%s)"%(a,b) + raise ValueError("f must have a sign change in the interval (%s,%s)"%(a,b)) intervals.append((a,b)) round += 1 return c, intervals diff --git a/src/sage/interfaces/axiom.py b/src/sage/interfaces/axiom.py index af41e70fc65..c85e37719b7 100644 --- a/src/sage/interfaces/axiom.py +++ b/src/sage/interfaces/axiom.py @@ -262,7 +262,7 @@ def _read_in_file_command(self, filename): '22' """ if not filename.endswith('.input'): - raise ValueError, "the filename must end with .input" + raise ValueError("the filename must end with .input") # For some reason this trivial comp # keeps certain random freezes from occurring. Do not remove this. @@ -387,7 +387,7 @@ def set(self, var, value): out = self._eval_line(cmd, reformat=False) if out.find("error") != -1: - raise TypeError, "Error executing code in Axiom\nCODE:\n\t%s\nAxiom ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Axiom\nCODE:\n\t%s\nAxiom ERROR:\n\t%s"%(cmd, out)) def get(self, var): @@ -425,7 +425,7 @@ def _eval_line(self, line, reformat=True, allow_use_file=False, if line == '': return '' if len(line) > 3000: - raise NotImplementedError, "evaluation of long input lines (>3000 characters) in Axiom not yet implemented." + raise NotImplementedError("evaluation of long input lines (>3000 characters) in Axiom not yet implemented.") if self._expect is None: self._start() if allow_use_file and self.__eval_using_file_cutoff and \ @@ -449,7 +449,7 @@ def _eval_line(self, line, reformat=True, allow_use_file=False, if '>> Error detected within library code:' in out or \ 'Cannot find a definition or applicable library operation named' in out: - raise RuntimeError, out + raise RuntimeError(out) if not reformat: return out @@ -671,7 +671,7 @@ def __getitem__(self, n): """ n = int(n) if n <= 0 or n > len(self): - raise IndexError, "index out of range" + raise IndexError("index out of range") P = self._check_valid() if not isinstance(n, tuple): return P.new('%s(%s)'%(self._name, n)) @@ -725,7 +725,7 @@ def _latex_(self): P = self.parent() s = P._eval_line('outputAsTex(%s)'%self.name(), reformat=False) if not '$$' in s: - raise RuntimeError, "Error texing axiom object." + raise RuntimeError("Error texing axiom object.") i = s.find('$$') j = s.rfind('$$') s = s[i+2:j] diff --git a/src/sage/interfaces/chomp.py b/src/sage/interfaces/chomp.py index 65a783d39a0..b2e413480d5 100644 --- a/src/sage/interfaces/chomp.py +++ b/src/sage/interfaces/chomp.py @@ -142,7 +142,7 @@ def __call__(self, program, complex, subcomplex=None, **kwds): from sage.combinat.free_module import CombinatorialFreeModule if not have_chomp(program): - raise OSError, "Program %s not found" % program + raise OSError("Program %s not found" % program) verbose = kwds.get('verbose', False) generators = kwds.get('generators', False) @@ -179,7 +179,7 @@ def __call__(self, program, complex, subcomplex=None, **kwds): print "Chain complex over %s" % base_ring if base_ring == QQ: - raise ValueError, "CHomP doesn't compute over the rationals, only over Z or F_p." + raise ValueError("CHomP doesn't compute over the rationals, only over Z or F_p.") if base_ring.is_prime_field(): p = base_ring.characteristic() extra_opts.append('-p%s' % p) @@ -193,7 +193,7 @@ def __call__(self, program, complex, subcomplex=None, **kwds): try: data = complex._chomp_repr_() except AttributeError: - raise AttributeError, "Complex can not be converted to use with CHomP." + raise AttributeError("Complex can not be converted to use with CHomP.") datafile = tmp_filename() f = open(datafile, 'w') @@ -228,7 +228,7 @@ def __call__(self, program, complex, subcomplex=None, **kwds): try: sub = subcomplex._chomp_repr_() except AttributeError: - raise AttributeError, "Subcomplex can not be converted to use with CHomP." + raise AttributeError("Subcomplex can not be converted to use with CHomP.") subfile = tmp_filename() f = open(subfile, 'w') f.write(sub) @@ -485,7 +485,7 @@ def homsimpl(complex=None, subcomplex=None, **kwds): and (subcomplex is None or isinstance(subcomplex, SimplicialComplex))): return CHomP()('homsimpl', complex, subcomplex=subcomplex, **kwds) else: - raise TypeError, "Complex and/or subcomplex are not simplicial complexes." + raise TypeError("Complex and/or subcomplex are not simplicial complexes.") def homcubes(complex=None, subcomplex=None, **kwds): r""" @@ -534,7 +534,7 @@ def homcubes(complex=None, subcomplex=None, **kwds): and (subcomplex is None or isinstance(subcomplex, CubicalComplex))): return CHomP()('homcubes', complex, subcomplex=subcomplex, **kwds) else: - raise TypeError, "Complex and/or subcomplex are not cubical complexes." + raise TypeError("Complex and/or subcomplex are not cubical complexes.") def homchain(complex=None, **kwds): r""" @@ -588,7 +588,7 @@ def homchain(complex=None, **kwds): if isinstance(complex, ChainComplex_class): return CHomP()('homchain', complex, **kwds) else: - raise TypeError, "Complex is not a chain complex." + raise TypeError("Complex is not a chain complex.") def process_generators_cubical(gen_string, dim): r""" diff --git a/src/sage/interfaces/expect.py b/src/sage/interfaces/expect.py index 04ec9e8ced9..69b96afbfc0 100644 --- a/src/sage/interfaces/expect.py +++ b/src/sage/interfaces/expect.py @@ -430,8 +430,8 @@ def _start(self, alt_message=None, block_during_init=True): self._expect = None self._session_number = BAD_SESSION failed_to_start.append(self.name()) - raise RuntimeError, "Unable to start %s because the command '%s' failed.\n%s"%( - self.name(), cmd, self._install_hints()) + raise RuntimeError("Unable to start %s because the command '%s' failed.\n%s"%( + self.name(), cmd, self._install_hints())) os.chdir(current_path) self._expect.timeout = self.__max_startup_time @@ -445,7 +445,7 @@ def _start(self, alt_message=None, block_during_init=True): self._expect = None self._session_number = BAD_SESSION failed_to_start.append(self.name()) - raise RuntimeError, "Unable to start %s"%self.name() + raise RuntimeError("Unable to start %s"%self.name()) self._expect.timeout = None with gc_disabled(): if block_during_init: @@ -700,10 +700,10 @@ def _eval_line_using_file(self, line, restart_if_needed=True): self._synchronize() return self._post_process_from_file(self._eval_line_using_file(line, restart_if_needed=False)) except RuntimeError as msg: - raise RuntimeError, '%s terminated unexpectedly while reading in a large line:\n%s'%(self,msg[0]) + raise RuntimeError('%s terminated unexpectedly while reading in a large line:\n%s'%(self,msg[0])) except TypeError: pass - raise RuntimeError, '%s terminated unexpectedly while reading in a large line'%self + raise RuntimeError('%s terminated unexpectedly while reading in a large line'%self) except RuntimeError as msg: if self._quit_string() in line: if self._expect is None or not self._expect.isalive(): @@ -716,10 +716,10 @@ def _eval_line_using_file(self, line, restart_if_needed=True): except TypeError: pass except RuntimeError as msg: - raise RuntimeError, '%s terminated unexpectedly while reading in a large line'%self + raise RuntimeError('%s terminated unexpectedly while reading in a large line'%self) if "Input/output error" in msg[0]: # This occurs on non-linux machines - raise RuntimeError, '%s terminated unexpectedly while reading in a large line'%self - raise RuntimeError, '%s terminated unexpectedly while reading in a large line:\n%s'%(self,msg[0]) + raise RuntimeError('%s terminated unexpectedly while reading in a large line'%self) + raise RuntimeError('%s terminated unexpectedly while reading in a large line:\n%s'%(self,msg[0])) return self._post_process_from_file(s) def _post_process_from_file(self, s): @@ -814,7 +814,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if E = self._expect try: if len(line) >= 4096: - raise RuntimeError, "Sending more than 4096 characters with %s on a line may cause a hang and you're sending %s characters"%(self, len(line)) + raise RuntimeError("Sending more than 4096 characters with %s on a line may cause a hang and you're sending %s characters"%(self, len(line))) E.sendline(line) if wait_for_prompt == False: return '' @@ -854,7 +854,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if else: tmp_to_use = self._remote_tmpfile() if self._read_in_file_command(tmp_to_use) in line: - raise pexpect.EOF, msg + raise pexpect.EOF(msg) except NotImplementedError: pass if self._quit_string() in line: @@ -866,13 +866,13 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if return self._eval_line(line,allow_use_file=allow_use_file, wait_for_prompt=wait_for_prompt, restart_if_needed=False) except (TypeError, RuntimeError): pass - raise RuntimeError, "%s\n%s crashed executing %s"%(msg,self, line) + raise RuntimeError("%s\n%s crashed executing %s"%(msg,self, line)) out = E.before else: out = '\n\r' except KeyboardInterrupt: self._keyboard_interrupt() - raise KeyboardInterrupt, "Ctrl-c pressed while running %s"%self + raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self) i = out.find("\n") j = out.rfind("\r") return out[i+1:j].replace('\r\n','\n') @@ -885,12 +885,12 @@ def _keyboard_interrupt(self): except pexpect.ExceptionPexpect as msg: raise pexpect.ExceptionPexpect( "THIS IS A BUG -- PLEASE REPORT. This should never happen.\n" + msg) self._start() - raise KeyboardInterrupt, "Restarting %s (WARNING: all variables defined in previous session are now invalid)"%self + raise KeyboardInterrupt("Restarting %s (WARNING: all variables defined in previous session are now invalid)"%self) else: self._expect.sendline(chr(3)) # send ctrl-c self._expect.expect(self._prompt) self._expect.expect(self._prompt) - raise KeyboardInterrupt, "Ctrl-c pressed while running %s"%self + raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self) def interrupt(self, tries=20, timeout=0.3, quit_on_fail=True): E = self._expect @@ -1032,7 +1032,7 @@ def _expect_expr(self, expr=None, timeout=None): if i > 0: v = self._expect.before self.quit() - raise ValueError, "%s\nComputation failed due to a bug in %s -- NOTE: Had to restart."%(v, self) + raise ValueError("%s\nComputation failed due to a bug in %s -- NOTE: Had to restart."%(v, self)) except KeyboardInterrupt as msg: i = 0 while True: @@ -1049,7 +1049,7 @@ def _expect_expr(self, expr=None, timeout=None): pass else: break - raise KeyboardInterrupt, msg + raise KeyboardInterrupt(msg) def _sendstr(self, str): r""" @@ -1193,7 +1193,7 @@ def eval(self, code, strip=True, synchronize=False, locals=None, allow_use_file= pass if not isinstance(code, basestring): - raise TypeError, 'input code must be a string.' + raise TypeError('input code must be a string.') #Remove extra whitespace code = code.strip() @@ -1212,7 +1212,7 @@ def eval(self, code, strip=True, synchronize=False, locals=None, allow_use_file= # by _eval_line # In particular, do NOT call self._keyboard_interrupt() except TypeError as s: - raise TypeError, 'error evaluating "%s":\n%s'%(code,s) + raise TypeError('error evaluating "%s":\n%s'%(code,s)) ############################################################ # Functions for working with variables. @@ -1318,9 +1318,9 @@ def _check_valid(self): P = self.parent() if P is None or P._session_number == BAD_SESSION or self._session_number == -1 or \ P._session_number != self._session_number: - raise ValueError, "The %s session in which this object was defined is no longer running."%P.name() + raise ValueError("The %s session in which this object was defined is no longer running."%P.name()) except AttributeError: - raise ValueError, "The session in which this object was defined is no longer running." + raise ValueError("The session in which this object was defined is no longer running.") return P def __del__(self): diff --git a/src/sage/interfaces/gap.py b/src/sage/interfaces/gap.py index 4a4127029a4..a3ee8d769b0 100644 --- a/src/sage/interfaces/gap.py +++ b/src/sage/interfaces/gap.py @@ -659,7 +659,7 @@ def _keyboard_interrupt(self): """ print "Interrupting %s..."%self self.quit() - raise KeyboardInterrupt, "Ctrl-c pressed while running %s"%self + raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self) def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=True): """ @@ -741,7 +741,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if self.quit() gap_reset_workspace() error = error.replace('\r','') - raise RuntimeError, "%s produced error output\n%s\n executing %s"%(self, error,line) + raise RuntimeError("%s produced error output\n%s\n executing %s"%(self, error,line)) if len(normal) == 0: return '' @@ -768,11 +768,11 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if else: return '' else: - raise RuntimeError, message + raise RuntimeError(message) except KeyboardInterrupt: self._keyboard_interrupt() - raise KeyboardInterrupt, "Ctrl-c pressed while running %s"%self + raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self) def unbind(self, var): """ @@ -966,7 +966,7 @@ def __repr__(self): """ s = ExpectElement.__repr__(self) if s.find('must have a value') != -1: - raise RuntimeError, "An error occurred creating an object in %s from:\n'%s'\n%s"%(self.parent().name(), self._create, s) + raise RuntimeError("An error occurred creating an object in %s from:\n'%s'\n%s"%(self.parent().name(), self._create, s)) return s def bool(self): @@ -1760,7 +1760,7 @@ def intmod_gap_to_sage(x): m = re.match(r'Zmod[np]ZObj\( ([0-9]*), ([0-9]*) \)', s) if m: return Mod(m.group(1), m.group(2)) - raise ValueError, "Unable to convert Gap element '%s'" % s + raise ValueError("Unable to convert Gap element '%s'" % s) ############# diff --git a/src/sage/interfaces/gap3.py b/src/sage/interfaces/gap3.py index a64f7705da5..73a83dcd627 100644 --- a/src/sage/interfaces/gap3.py +++ b/src/sage/interfaces/gap3.py @@ -679,7 +679,7 @@ def __init__(self, parent, value, is_name=False, name=None): # Warning: One should not redefine E, X or Z in gap3, because # things will break, but gap3 raises no errors if one does this! if name in ["E","X","Z"]: - raise ValueError, "you are attempting to redefine %s; but you should never redefine E, X or Z in gap3 (because things will break!)" % name + raise ValueError("you are attempting to redefine %s; but you should never redefine E, X or Z in gap3 (because things will break!)" % name) # initialize the superclass super(GAP3Element, self).__init__(parent, value, is_name, name) diff --git a/src/sage/interfaces/genus2reduction.py b/src/sage/interfaces/genus2reduction.py index 326353ab69f..6b548105e5d 100644 --- a/src/sage/interfaces/genus2reduction.py +++ b/src/sage/interfaces/genus2reduction.py @@ -385,9 +385,9 @@ def raw(self, Q, P): P = R(P) Q = R(Q) if P.degree() > 6: - raise ValueError, "P (=%s) must have degree at most 6"%P + raise ValueError("P (=%s) must have degree at most 6"%P) if Q.degree() >=4: - raise ValueError, "Q (=%s) must have degree at most 3"%Q + raise ValueError("Q (=%s) must have degree at most 3"%Q) E = self.__expect try: @@ -398,7 +398,7 @@ def raw(self, Q, P): # a bad state, and quitting it fixes things, since next # time it is used, it is started cleanly. See trac 5573. E.quit() - raise ValueError, "error in input; possibly singular curve? (Q=%s, P=%s)"%(Q,P) + raise ValueError("error in input; possibly singular curve? (Q=%s, P=%s)"%(Q,P)) i = s.find('a minimal') j = s.rfind(']') return s[i:j+2], Q, P diff --git a/src/sage/interfaces/gfan.py b/src/sage/interfaces/gfan.py index 6d8d02ab897..7170df1641e 100644 --- a/src/sage/interfaces/gfan.py +++ b/src/sage/interfaces/gfan.py @@ -63,7 +63,7 @@ def __call__(self, I, cmd='',verbose = False, format=True): # since version 0.4, gfan indicates which LP algorithm it is using. # we avoid interpreting this as an error if (len(err) > 0) and not (err.startswith('LP algorithm being used:')): - raise RuntimeError, err + raise RuntimeError(err) return ans diff --git a/src/sage/interfaces/giac.py b/src/sage/interfaces/giac.py index d277d5a3d5c..0948fa1349f 100644 --- a/src/sage/interfaces/giac.py +++ b/src/sage/interfaces/giac.py @@ -319,7 +319,7 @@ def _keyboard_interrupt(self): self._expect.sendline(chr(3)) # send ctrl-c self._expect.expect(self._prompt) # self._expect.expect(self._prompt) - raise RuntimeError, "Ctrl-c pressed while running %s"%self + raise RuntimeError("Ctrl-c pressed while running %s"%self) def __reduce__(self): """ @@ -567,7 +567,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if z = Expect._eval_line(self, line, allow_use_file=allow_use_file, wait_for_prompt=wait_for_prompt) if z.lower().find("error") != -1: - raise RuntimeError, "An error occurred running a Giac command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z) + raise RuntimeError("An error occurred running a Giac command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z)) return z @@ -616,7 +616,7 @@ def set(self, var, value): cmd = '%s:=%s:;'%(var,value) #if giac is not in maple mode ( maple_mode(0)) out = self.eval(cmd) if out.find("error") != -1: - raise TypeError, "Error executing code in Giac\nCODE:\n\t%s\nGiac ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Giac\nCODE:\n\t%s\nGiac ERROR:\n\t%s"%(cmd, out)) def get(self, var): @@ -897,7 +897,7 @@ def __cmp__(self, other): else: return 1 else: - raise RuntimeError, e + raise RuntimeError(e) if P.eval("evalb(%s %s %s)"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): return 1 # everything is supposed to be comparable in Python, so we define @@ -1049,7 +1049,7 @@ def _sage_(self): from sage.symbolic.all import SR return SR(result) except Exception: - raise NotImplementedError, "Unable to parse Giac output: %s" % result + raise NotImplementedError("Unable to parse Giac output: %s" % result) else: return [entry.sage() for entry in self] @@ -1090,7 +1090,7 @@ def integral(self, var='x', min=None, max=None): return giac('int(%s,%s)'%(self.name(),var)) else: if max is None: - raise ValueError, "neither or both of min/max must be specified." + raise ValueError("neither or both of min/max must be specified.") return giac('int(%s,%s,%s,%s)'%(self.name(),var,giac(min),giac(max))) integrate=integral @@ -1122,7 +1122,7 @@ def sum(self, var, min=None, max=None): return giac('sum(%s,%s)'%(self.name(),var)) else: if max is None: - raise ValueError, "neither or both of min/max must be specified." + raise ValueError("neither or both of min/max must be specified.") return giac('sum(%s,%s,%s,%s)'%(self.name(),var,giac(min),giac(max))) diff --git a/src/sage/interfaces/gnuplot.py b/src/sage/interfaces/gnuplot.py index 54646b5e58f..c4ed3555acc 100644 --- a/src/sage/interfaces/gnuplot.py +++ b/src/sage/interfaces/gnuplot.py @@ -36,7 +36,7 @@ def gnuplot(self): self._gnuplot = GP.Gnuplot() return self._gnuplot except ImportError: - raise RuntimeError, "Install the gnuplotpy Python module." + raise RuntimeError("Install the gnuplotpy Python module.") def __call__(self, line): return self.gnuplot()(line) diff --git a/src/sage/interfaces/gp.py b/src/sage/interfaces/gp.py index e4e7eb5453a..767c6689ea4 100644 --- a/src/sage/interfaces/gp.py +++ b/src/sage/interfaces/gp.py @@ -395,7 +395,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if verbose("automatically doubling the PARI stack and re-executing current input line") b = self.eval("allocatemem()") if b.find("Warning: not enough memory") != -1: - raise RuntimeError, a + raise RuntimeError(a) return self._eval_line(line, allow_use_file=allow_use_file, wait_for_prompt=wait_for_prompt) else: @@ -508,7 +508,7 @@ def set(self, var, value): cmd = '%s=%s;'%(var,value) out = self.eval(cmd) if out.find('***') != -1: - raise TypeError, "Error executing code in GP:\nCODE:\n\t%s\nPARI/GP ERROR:\n%s"%(cmd, out) + raise TypeError("Error executing code in GP:\nCODE:\n\t%s\nPARI/GP ERROR:\n%s"%(cmd, out)) def get(self, var): diff --git a/src/sage/interfaces/interface.py b/src/sage/interfaces/interface.py index f2ab0bda99f..4d77e9116c0 100644 --- a/src/sage/interfaces/interface.py +++ b/src/sage/interfaces/interface.py @@ -141,7 +141,7 @@ def eval(self, code, locals=None, **kwds): """ if not isinstance(code, basestring): - raise TypeError, 'input code must be a string.' + raise TypeError('input code must be a string.') #Remove extra whitespace code = code.strip() @@ -152,7 +152,7 @@ def eval(self, code, locals=None, **kwds): # by _eval_line # In particular, do NOT call self._keyboard_interrupt() except TypeError as s: - raise TypeError, 'error evaluating "%s":\n%s'%(code,s) + raise TypeError('error evaluating "%s":\n%s'%(code,s)) _eval_line = eval @@ -209,7 +209,7 @@ def __call__(self, x, name=None): try: return cls(self, str(x), name=name) except TypeError as msg2: - raise TypeError, msg + raise TypeError(msg) def _coerce_from_special_method(self, x): """ @@ -258,7 +258,7 @@ def _coerce_impl(self, x, use_special=True): r.__sage_list = z # do this to avoid having the entries of the list be garbage collected return r - raise TypeError, "unable to coerce element into %s"%self.name() + raise TypeError("unable to coerce element into %s"%self.name()) def new(self, code): return self(code) @@ -468,7 +468,7 @@ def _check_valid_function_name(self, function): AttributeError """ if function == '': - raise ValueError, "function name must be nonempty" + raise ValueError("function name must be nonempty") if function[:2] == "__": raise AttributeError @@ -623,7 +623,7 @@ def __init__(self, parent, value, is_name=False, name=None): try: self._name = parent._create(value, name=name) except (TypeError, RuntimeError, ValueError) as x: - raise TypeError, x + raise TypeError(x) def _latex_(self): # return "\\begin{verbatim}%s\\end{verbatim}"%self @@ -764,9 +764,9 @@ def _check_valid(self): try: P = self.parent() if P is None: - raise ValueError, "The %s session in which this object was defined is no longer running."%P.name() + raise ValueError("The %s session in which this object was defined is no longer running."%P.name()) except AttributeError: - raise ValueError, "The session in which this object was defined is no longer running." + raise ValueError("The session in which this object was defined is no longer running.") return P def __del__(self): @@ -852,7 +852,7 @@ def _sage_(self): try: return sage.misc.sage_eval.sage_eval(string) except Exception: - raise NotImplementedError, "Unable to parse output: %s" % string + raise NotImplementedError("Unable to parse output: %s" % string) def sage(self): @@ -1057,7 +1057,7 @@ def name(self, new_name=None): """ if new_name is not None: if not isinstance(new_name, str): - raise TypeError, "new_name must be a string" + raise TypeError("new_name must be a string") p = self.parent() p.set(new_name, self._name) return p._object_class()(p, new_name, is_name=True) @@ -1073,7 +1073,7 @@ def _operation(self, operation, right): try: return P.new('%s %s %s'%(self._name, operation, right._name)) except Exception as msg: - raise TypeError, msg + raise TypeError(msg) def _add_(self, right): """ diff --git a/src/sage/interfaces/kash.py b/src/sage/interfaces/kash.py index 78867cd8c86..6817f394113 100644 --- a/src/sage/interfaces/kash.py +++ b/src/sage/interfaces/kash.py @@ -517,7 +517,7 @@ def _start(self): try: Expect._start(self) except RuntimeError: - raise RuntimeError, "You must install the optional Kash package to use Kash from Sage." + raise RuntimeError("You must install the optional Kash package to use Kash from Sage.") # Turn off the annoying timer. self.eval('Time(false);') @@ -629,7 +629,7 @@ def set(self, var, value): #out = self.eval(cmd) out = self._eval_line(cmd, allow_use_file=True) if out.lower().find('error') != -1: - raise TypeError, "Error executing code in Kash\nCODE:\n\t%s\nKash ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Kash\nCODE:\n\t%s\nKash ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ diff --git a/src/sage/interfaces/lie.py b/src/sage/interfaces/lie.py index 2106f97ba8d..7c91dd89be8 100644 --- a/src/sage/interfaces/lie.py +++ b/src/sage/interfaces/lie.py @@ -626,7 +626,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if #Check to see if an error has occurred err = max( out.find("\n(in"), out.find('not defined'), out.find('Argument types') ) if err != -1: - raise RuntimeError, "An error occurred running a LiE command:\n%s"%(out.replace('\r\n','\n')) + raise RuntimeError("An error occurred running a LiE command:\n%s"%(out.replace('\r\n','\n'))) return out @@ -656,7 +656,7 @@ def set(self, var, value): out = self.eval(cmd) i = min( out.find('not defined'), out.find('\(in'), out.find('Argument types') ) if i != -1: - raise RuntimeError, out + raise RuntimeError(out) def get(self, var): """ @@ -756,7 +756,7 @@ def _matrix_(self, R=None): m = m.change_ring(R) return m else: - raise ValueError, "not a matrix" + raise ValueError("not a matrix") def _sage_(self): @@ -772,7 +772,7 @@ def _sage_(self): """ t = self.type() if t == 'grp': - raise ValueError, "cannot convert Lie groups to native Sage objects" + raise ValueError("cannot convert Lie groups to native Sage objects") elif t == 'mat': import sage.matrix.constructor return sage.matrix.constructor.matrix( eval( str(self).replace('\n','').strip()) ) diff --git a/src/sage/interfaces/lisp.py b/src/sage/interfaces/lisp.py index 58f0878d932..3e8c436c625 100644 --- a/src/sage/interfaces/lisp.py +++ b/src/sage/interfaces/lisp.py @@ -166,7 +166,7 @@ def set(self, var, value): cmd = '(setq %s %s)'%(var, value) out = self.eval(cmd) if '***' in out: - raise TypeError, "Error executing code in Sage\nCODE:\n\t%s\nSAGE ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Sage\nCODE:\n\t%s\nSAGE ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ @@ -372,7 +372,7 @@ def _equality_symbol(self): ... NotImplementedError: ... """ - raise NotImplementedError, ("We should never reach here in the Lisp interface. " + + raise NotImplementedError("We should never reach here in the Lisp interface. " + "Please report this as a bug.") def help(self, command): diff --git a/src/sage/interfaces/macaulay2.py b/src/sage/interfaces/macaulay2.py index 812a601013f..d5636715609 100644 --- a/src/sage/interfaces/macaulay2.py +++ b/src/sage/interfaces/macaulay2.py @@ -299,7 +299,7 @@ def set(self, var, value): cmd = '%s=%s;'%(var,value) ans = Expect.eval(self, cmd) if ans.find("stdio:") != -1: - raise RuntimeError, "Error evaluating Macaulay2 code.\nIN:%s\nOUT:%s"%(cmd, ans) + raise RuntimeError("Error evaluating Macaulay2 code.\nIN:%s\nOUT:%s"%(cmd, ans)) def _object_class(self): """ @@ -625,7 +625,7 @@ def external_string(self): if 'stdio:' in X: if 'to external string' in X: return P.eval('%s'%self.name()) - raise RuntimeError, "Error evaluating Macaulay2 code.\nIN:%s\nOUT:%s"%(code, X) + raise RuntimeError("Error evaluating Macaulay2 code.\nIN:%s\nOUT:%s"%(code, X)) s = multiple_replace({'\r':'', '\n':' '}, X) return s @@ -667,7 +667,7 @@ def __setitem__(self, index, value): value = P(value) res = P.eval("%s # %s = %s"%(self.name(), index.name(), value.name())) if "assignment attempted to element of immutable list" in res: - raise TypeError, "item assignment not supported" + raise TypeError("item assignment not supported") def __call__(self, x): """ @@ -1038,7 +1038,7 @@ def to_sage(self): # Check that we are dealing with default degrees, i.e. 1's. if self.degrees().any("x -> x != {1}").to_sage(): - raise ValueError, "cannot convert Macaulay2 polynomial ring with non-default degrees to Sage" + raise ValueError("cannot convert Macaulay2 polynomial ring with non-default degrees to Sage") #Handle the term order external_string = self.external_string() order = None @@ -1049,7 +1049,7 @@ def to_sage(self): if order_name in external_string: order = inv_macaulay2_name_mapping[order_name] if len(gens) > 1 and order is None: - raise ValueError, "cannot convert Macaulay2's term order to a Sage term order" + raise ValueError("cannot convert Macaulay2's term order to a Sage term order") return PolynomialRing(base_ring, order=order, names=gens) elif cls_str == "GaloisField": @@ -1098,7 +1098,7 @@ def to_sage(self): try: return sage_eval(repr_str) except Exception: - raise NotImplementedError, "cannot convert %s to a Sage object"%repr_str + raise NotImplementedError("cannot convert %s to a Sage object"%repr_str) class Macaulay2Function(ExpectFunction): diff --git a/src/sage/interfaces/magma.py b/src/sage/interfaces/magma.py index c9910a007ff..e0e5734164a 100644 --- a/src/sage/interfaces/magma.py +++ b/src/sage/interfaces/magma.py @@ -416,7 +416,7 @@ def _post_process_from_file(self, s): '' """ if not isinstance(s, str): - raise RuntimeError, "Error evaluating object in %s:\n%s"%(self,s) + raise RuntimeError("Error evaluating object in %s:\n%s"%(self,s)) # Chop off the annoying "Loading ... " message that Magma # always outputs no matter what. i = s.find('\n') @@ -536,7 +536,7 @@ def eval(self, x, strip=True, **kwds): x += ';' ans = Expect.eval(self, x, **kwds).replace('\\\n','') if 'Runtime error' in ans or 'User error' in ans: - raise RuntimeError, "Error evaluating Magma code.\nIN:%s\nOUT:%s"%(x, ans) + raise RuntimeError("Error evaluating Magma code.\nIN:%s\nOUT:%s"%(x, ans)) return ans def _preparse(self, s): @@ -599,7 +599,7 @@ def set(self, var, value): """ out = self.eval("%s:=%s"%(var, value)) if out.lower().find("error") != -1: - raise TypeError, "Error executing Magma code:\n%s"%out + raise TypeError("Error executing Magma code:\n%s"%out) def get(self, var): """ @@ -665,7 +665,7 @@ def objgens(self, value, gens): value = self(value) out = self.eval("_zsage_<%s> := %s; %s := _zsage_"%(gens, value.name(), var)) if out.lower().find("error") != -1: - raise TypeError, "Error executing Magma code:\n%s"%out + raise TypeError("Error executing Magma code:\n%s"%out) return self(var) def __call__(self, x, gens=None): @@ -977,7 +977,7 @@ def attach_spec(self, filename): """ s = self.eval('AttachSpec("%s")'%filename) if s: - raise RuntimeError, s.strip() + raise RuntimeError(s.strip()) AttachSpec = attach_spec @@ -1175,7 +1175,7 @@ def _do_call(self, code, nvals): ans = tuple([MagmaElement(self, x, is_name = True) for x in v]) if out.lower().find("error") != -1: - raise TypeError, "Error executing Magma code:\n%s"%out + raise TypeError("Error executing Magma code:\n%s"%out) return ans def bar_call(self, left, name, gens, nvals=1): @@ -1559,7 +1559,7 @@ def SetVerbose(self, type, level): 2 """ if level < 0: - raise TypeError, "level must be >= 0" + raise TypeError("level must be >= 0") self.eval('SetVerbose("%s",%d)'%(type,level)) def get_verbose(self, type): @@ -2088,7 +2088,7 @@ def gen(self, n): IndexError: list index out of range """ if n <= 0: - raise IndexError, "index must be positive since Magma indexes are 1-based" + raise IndexError("index must be positive since Magma indexes are 1-based") return self.gens()[n-1] def gens(self): diff --git a/src/sage/interfaces/maple.py b/src/sage/interfaces/maple.py index 68b93c68f87..a6d35101737 100644 --- a/src/sage/interfaces/maple.py +++ b/src/sage/interfaces/maple.py @@ -302,7 +302,7 @@ def _keyboard_interrupt(self): self._expect.sendline(chr(3)) # send ctrl-c self._expect.expect(self._prompt) self._expect.expect(self._prompt) - raise RuntimeError, "Ctrl-c pressed while running %s"%self + raise RuntimeError("Ctrl-c pressed while running %s"%self) def __reduce__(self): """ @@ -556,7 +556,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if e.sendline('%s__sage__;'%(chr(8)*len(line))) e.expect('__sage__;') e.expect(self._prompt) - raise RuntimeError, "An error occurred running a Maple command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z) + raise RuntimeError("An error occurred running a Maple command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z)) return z def cputime(self, t=None): @@ -594,7 +594,7 @@ def set(self, var, value): cmd = '%s:=%s:'%(var,value) out = self.eval(cmd) if out.find("error") != -1: - raise TypeError, "Error executing code in Maple\nCODE:\n\t%s\nMaple ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Maple\nCODE:\n\t%s\nMaple ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ @@ -701,7 +701,7 @@ def _source(self, s): cmd = 'echo "interface(verboseproc=2): print(%s);" | maple -q'%s src = os.popen(cmd).read() if src.strip() == s: - raise RuntimeError, "no source code could be found" + raise RuntimeError("no source code could be found") else: return src @@ -981,7 +981,7 @@ def __cmp__(self, other): else: return 1 else: - raise RuntimeError, e + raise RuntimeError(e) if P.eval("evalb(%s %s %s)"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): return 1 # everything is supposed to be comparable in Python, so we define @@ -1022,7 +1022,7 @@ def _mul_(self, right): try: return P.new('%s . %s'%(self._name, right._name)) except Exception as msg: - raise TypeError,msg + raise TypeError(msg) def trait_names(self): """ @@ -1101,7 +1101,7 @@ def _sage_(self): from sage.symbolic.all import SR return SR(result) except Exception: - raise NotImplementedError, "Unable to parse Maple output: %s" % result + raise NotImplementedError("Unable to parse Maple output: %s" % result) # An instance maple = Maple(script_subdirectory='user') diff --git a/src/sage/interfaces/mathematica.py b/src/sage/interfaces/mathematica.py index f60372ba27c..170bae7f98b 100644 --- a/src/sage/interfaces/mathematica.py +++ b/src/sage/interfaces/mathematica.py @@ -509,7 +509,7 @@ def set(self, var, value): #out = self.eval(cmd) out = self._eval_line(cmd, allow_use_file=True) if len(out) > 8: - raise TypeError, "Error executing code in Mathematica\nCODE:\n\t%s\nMathematica ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Mathematica\nCODE:\n\t%s\nMathematica ERROR:\n\t%s"%(cmd, out)) def get(self, var, ascii_art=False): """ @@ -743,8 +743,8 @@ def _sage_(self, locals={}): # Get Mathematica's output and perform preliminary formatting res = self._sage_repr() if '"' in res: - raise NotImplementedError, "String conversion from Mathematica \ - does not work. Mathematica's output was: %s" % res + raise NotImplementedError("String conversion from Mathematica \ + does not work. Mathematica's output was: %s" % res) # Find all the mathematica functions, constants and symbolic variables # present in `res`. Convert MMA functions and constants to their @@ -783,9 +783,9 @@ def _sage_(self, locals={}): lsymbols[m.group()] = f break else: - raise NotImplementedError, "Don't know a Sage equivalent \ + raise NotImplementedError("Don't know a Sage equivalent \ for Mathematica function '%s'. Please specify one \ - manually using the 'locals' dictionary" % m.group() + manually using the 'locals' dictionary" % m.group()) # Check if Sage has an equivalent constant else: for t in autotrans: @@ -798,8 +798,8 @@ def _sage_(self, locals={}): return symbolic_expression_from_string(res, lsymbols, accept_sequence=True) except Exception: - raise NotImplementedError, "Unable to parse Mathematica \ - output: %s" % res + raise NotImplementedError("Unable to parse Mathematica \ + output: %s" % res) def __str__(self): P = self._check_valid() diff --git a/src/sage/interfaces/matlab.py b/src/sage/interfaces/matlab.py index d1e2940a8c7..cd216db08a3 100644 --- a/src/sage/interfaces/matlab.py +++ b/src/sage/interfaces/matlab.py @@ -248,7 +248,7 @@ def set(self, var, value): cmd = '%s=%s;'%(var,value) out = self.eval(cmd) if out.find("error") != -1: - raise TypeError, "Error executing code in Matlab\nCODE:\n\t%s\nMatlab ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Matlab\nCODE:\n\t%s\nMatlab ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ @@ -323,7 +323,7 @@ def _object_class(self): class MatlabElement(ExpectElement): def __getitem__(self, n): - raise RuntimeError, "Use parenthesis for MATLAB matrices instead." + raise RuntimeError("Use parenthesis for MATLAB matrices instead.") def _matrix_(self, R): r""" diff --git a/src/sage/interfaces/maxima.py b/src/sage/interfaces/maxima.py index 63fb0bd183a..7603881f6a7 100644 --- a/src/sage/interfaces/maxima.py +++ b/src/sage/interfaces/maxima.py @@ -524,7 +524,7 @@ def __init__(self, script_subdirectory=None, logfile=None, server=None, SAGE_MAXIMA_DIR = os.path.join(DOT_SAGE,"maxima") if not os.path.exists(STARTUP): - raise RuntimeError, 'You must get the file local/bin/sage-maxima.lisp' + raise RuntimeError('You must get the file local/bin/sage-maxima.lisp') #self.__init_code = init_code if init_code is None: @@ -688,7 +688,7 @@ def _expect_expr(self, expr=None, timeout=None): #Note that this depends on the order of self._prompt_wait if expr is self._prompt_wait and i > len(self._ask): self.quit() - raise ValueError, "%s\nComputation failed due to a bug in Maxima -- NOTE: Maxima had to be restarted."%v + raise ValueError("%s\nComputation failed due to a bug in Maxima -- NOTE: Maxima had to be restarted."%v) j = v.find('Is ') v = v[j:] @@ -696,7 +696,7 @@ def _expect_expr(self, expr=None, timeout=None): msg = """Computation failed since Maxima requested additional constraints (try the command "maxima.assume('""" + v[4:k] +""">0')" before integral or limit evaluation, for example):\n""" + v + self._ask[i-1] self._sendline(";") self._expect_expr() - raise ValueError, msg + raise ValueError(msg) except KeyboardInterrupt as msg: #print self._expect.before i = 0 @@ -714,7 +714,7 @@ def _expect_expr(self, expr=None, timeout=None): pass else: break - raise KeyboardInterrupt, msg + raise KeyboardInterrupt(msg) def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True, restart_if_needed=False): @@ -919,7 +919,7 @@ def _error_msg(self, cmd, out): Maxima ERROR: Principal Value """ - raise TypeError, "Error executing code in Maxima\nCODE:\n\t%s\nMaxima ERROR:\n\t%s"%(cmd, out.replace('-- an error. To debug this try debugmode(true);','')) + raise TypeError("Error executing code in Maxima\nCODE:\n\t%s\nMaxima ERROR:\n\t%s"%(cmd, out.replace('-- an error. To debug this try debugmode(true);',''))) ########################################### # Direct access to underlying lisp interpreter. diff --git a/src/sage/interfaces/maxima_abstract.py b/src/sage/interfaces/maxima_abstract.py index a0b82897eff..cc147d4ab69 100644 --- a/src/sage/interfaces/maxima_abstract.py +++ b/src/sage/interfaces/maxima_abstract.py @@ -970,7 +970,7 @@ def unit_quadratic_integer(self, n): # n is not squarefree.) n = Integer(n).squarefree_part() if n < 1: - raise ValueError, "n (=%s) must be >= 1"%n + raise ValueError("n (=%s) must be >= 1"%n) s = repr(self('qunit(%s)'%n)).lower() r = re.compile('sqrt\(.*\)') s = r.sub('a', s) @@ -1575,7 +1575,7 @@ def integral(self, var='x', min=None, max=None): return I(var) else: if max is None: - raise ValueError, "neither or both of min/max must be specified." + raise ValueError("neither or both of min/max must be specified.") return I(var, min, max) integrate = integral @@ -1600,7 +1600,7 @@ def __float__(self): try: return float(repr(self.numer())) except ValueError: - raise TypeError, "unable to coerce '%s' to float"%repr(self) + raise TypeError("unable to coerce '%s' to float"%repr(self)) def __len__(self): """ @@ -1670,7 +1670,7 @@ def __getitem__(self, n): """ n = int(n) if n < 0 or n >= len(self): - raise IndexError, "n = (%s) must be between %s and %s"%(n, 0, len(self)-1) + raise IndexError("n = (%s) must be between %s and %s"%(n, 0, len(self)-1)) # If you change the n+1 to n below, better change __iter__ as well. return InterfaceElement.__getitem__(self, n+1) @@ -1763,7 +1763,7 @@ def _latex_(self): P = self.parent() s = P._eval_line('tex(%s);'%self.name(), reformat=False) if not '$$' in s: - raise RuntimeError, "Error texing Maxima object." + raise RuntimeError("Error texing Maxima object.") i = s.find('$$') j = s.rfind('$$') s = s[i+2:j] @@ -1909,7 +1909,7 @@ def _operation(self, operation, right): try: return P.new('%s %s %s'%(self._name, operation, right._name)) except Exception as msg: - raise TypeError, msg + raise TypeError(msg) class MaximaAbstractFunctionElement(InterfaceFunctionElement): diff --git a/src/sage/interfaces/maxima_lib.py b/src/sage/interfaces/maxima_lib.py index 7bf09dbae56..643ac0fc105 100644 --- a/src/sage/interfaces/maxima_lib.py +++ b/src/sage/interfaces/maxima_lib.py @@ -324,7 +324,7 @@ def __init__(self): """ global maxima_lib_instances if maxima_lib_instances > 0: - raise RuntimeError, "Maxima interface in library mode can only be instantiated once" + raise RuntimeError("Maxima interface in library mode can only be instantiated once") maxima_lib_instances += 1 global init_code @@ -737,12 +737,12 @@ def sr_integral(self,*args): if "Divergent" in s or "divergent" in s: # in pexpect interface, one looks for this - e.g. integrate(1/x^3,x,-1,3) gives a principal value # if "divergent" in s or 'Principal Value' in s: - raise ValueError, "Integral is divergent." + raise ValueError("Integral is divergent.") elif "Is" in s: # Maxima asked for a condition j = s.find('Is ') s = s[j:] k = s.find(' ',4) - raise ValueError, "Computation failed since Maxima requested additional constraints; using the 'assume' command before integral evaluation *may* help (example of legal syntax is 'assume(" + s[4:k] +">0)', see `assume?` for more details)\n" + s + raise ValueError("Computation failed since Maxima requested additional constraints; using the 'assume' command before integral evaluation *may* help (example of legal syntax is 'assume(" + s[4:k] +">0)', see `assume?` for more details)\n" + s) else: raise error @@ -785,12 +785,12 @@ def sr_sum(self,*args): # in pexpect interface, one looks for this; # could not find an example where 'Pole encountered' occurred, though # if "divergent" in s or 'Pole encountered' in s: - raise ValueError, "Sum is divergent." + raise ValueError("Sum is divergent.") elif "Is" in s: # Maxima asked for a condition j = s.find('Is ') s = s[j:] k = s.find(' ',4) - raise ValueError, "Computation failed since Maxima requested additional constraints; using the 'assume' command before summation *may* help (example of legal syntax is 'assume(" + s[4:k] +">0)', see `assume?` for more details)\n" + s + raise ValueError("Computation failed since Maxima requested additional constraints; using the 'assume' command before summation *may* help (example of legal syntax is 'assume(" + s[4:k] +">0)', see `assume?` for more details)\n" + s) else: raise error @@ -854,7 +854,7 @@ def sr_limit(self,expr,v,a,dir=None): if "Is" in s: # Maxima asked for a condition j = s.find('Is ') s = s[j:] - raise ValueError, "Computation failed since Maxima requested additional constraints; using the 'assume' command before limit evaluation *may* help (see `assume?` for more details)\n" + s + raise ValueError("Computation failed since Maxima requested additional constraints; using the 'assume' command before limit evaluation *may* help (see `assume?` for more details)\n" + s) else: raise error diff --git a/src/sage/interfaces/mupad.py b/src/sage/interfaces/mupad.py index 29f978ff260..d8cea1990f4 100644 --- a/src/sage/interfaces/mupad.py +++ b/src/sage/interfaces/mupad.py @@ -268,12 +268,12 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, z = E.before i = z.find(START) if i == -1: - raise RuntimeError, "%s\nError evaluating code in MuPAD"%z + raise RuntimeError("%s\nError evaluating code in MuPAD"%z) z = z[i+len(START)+2:] z = z.rstrip().rstrip(END).rstrip('"').rstrip().strip('\n').strip('\r').strip('\n').replace('\\\r\n','') i = z.find('Error: ') if i != -1: - raise RuntimeError, z[i + 7:] + raise RuntimeError(z[i + 7:]) return z def cputime(self, t=None): @@ -300,7 +300,7 @@ def set(self, var, value): out = self.eval(cmd) i = out.find('Error: ') if i != -1: - raise RuntimeError, out[i + 7:] + raise RuntimeError(out[i + 7:]) def get(self, var): """ diff --git a/src/sage/interfaces/mwrank.py b/src/sage/interfaces/mwrank.py index 6f39f73e10a..c4c7715a6d7 100644 --- a/src/sage/interfaces/mwrank.py +++ b/src/sage/interfaces/mwrank.py @@ -123,12 +123,12 @@ def validate_mwrank_input(s): if isinstance(s,(list,tuple)): from sage.rings.all import ZZ if len(s)!=5: - raise ValueError, "%s is not valid input to mwrank (should have 5 entries)" % s + raise ValueError("%s is not valid input to mwrank (should have 5 entries)" % s) try: ai = [ZZ(a) for a in s] return str(ai) except (TypeError,ValueError): - raise ValueError, "%s is not valid input to mwrank (entries should be integers)" % s + raise ValueError("%s is not valid input to mwrank (entries should be integers)" % s) if isinstance(s,str): if AINVS_PLAIN_RE.match(s): @@ -137,7 +137,7 @@ def validate_mwrank_input(s): ss = s.replace(' ','').replace('\n','').replace('\t','') if AINVS_LIST_RE.match(ss): return ss - raise ValueError, "%s is not valid input to mwrank" % s + raise ValueError("%s is not valid input to mwrank" % s) class Mwrank_class(Expect): """ @@ -263,13 +263,13 @@ def __call__(self, cmd): try: s = validate_mwrank_input(cmd) except ValueError as err: - raise ValueError, "Invalid input: %s" % err + raise ValueError("Invalid input: %s" % err) try: return self.eval(s) except ValueError as err: - raise ValueError, err + raise ValueError(err) except RuntimeError: - raise ValueError, cmd + raise ValueError(cmd) def eval(self, s, **kwds): """ @@ -316,9 +316,9 @@ def eval(self, s, **kwds): ss = validate_mwrank_input(s) return Expect.eval(self, ss, **kwds) except ValueError as err: - raise ValueError, 'Invalid input: %s' % err + raise ValueError('Invalid input: %s' % err) except RuntimeError: - raise ValueError, 'Invalid input (%s) to mwrank (singular curve)' % s + raise ValueError('Invalid input (%s) to mwrank (singular curve)' % s) def console(self): """ diff --git a/src/sage/interfaces/octave.py b/src/sage/interfaces/octave.py index a04643e7a16..290c44217ff 100644 --- a/src/sage/interfaces/octave.py +++ b/src/sage/interfaces/octave.py @@ -299,7 +299,7 @@ def set(self, var, value): cmd = '%s=%s;'%(var,value) out = self.eval(cmd) if out.find("error") != -1: - raise TypeError, "Error executing code in Octave\nCODE:\n\t%s\nOctave ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Octave\nCODE:\n\t%s\nOctave ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ @@ -394,7 +394,7 @@ def solve_linear_system(self, A, b): m = A.nrows() n = A.ncols() if m != len(b): - raise ValueError, "dimensions of A and b must be compatible" + raise ValueError("dimensions of A and b must be compatible") from sage.matrix.all import MatrixSpace from sage.rings.all import QQ MS = MatrixSpace(QQ,m,1) diff --git a/src/sage/interfaces/phc.py b/src/sage/interfaces/phc.py index 0431004a101..4a453715da5 100644 --- a/src/sage/interfaces/phc.py +++ b/src/sage/interfaces/phc.py @@ -449,7 +449,7 @@ def _output_from_command_list(self, command_list, polys, verbose = False): print read_stuff child_phc.close() if not os.path.exists(output_filename): - raise RuntimeError, "The output file does not exist; something went wrong running phc." + raise RuntimeError("The output file does not exist; something went wrong running phc.") # Delete the input file os.unlink(input_filename) @@ -479,7 +479,7 @@ def _input_file(self, polys): '2\nx^2 - 2*x + y - 1;\nx^2 + y^2 - 1;\n' """ if not isinstance(polys, (list, tuple)): - raise TypeError, 'polys must be a list or tuple' + raise TypeError('polys must be a list or tuple') s = '%s\n'%len(polys) for f in polys: s += f._repr_() + ';\n' # note the semicolon *terminators* @@ -514,7 +514,7 @@ def _parse_path_file(self, input_filename, verbose = False): """ if not os.path.exists(input_filename): - raise RuntimeError, "The file containing output from phc (" + input_filename + ") cannot be found" + raise RuntimeError("The file containing output from phc (" + input_filename + ") cannot be found") fh = open(input_filename) line_idx = 0 @@ -609,7 +609,7 @@ def _path_track_file(self, start_filename_or_string, polys, input_ring, c_skew = elif os.path.exists(start_filename_or_string): start_filename = start_filename_or_string else: - raise RuntimeError, "There is something wrong with your start string or filename" + raise RuntimeError("There is something wrong with your start string or filename") return self._output_from_command_list(['phc','0','0','A',start_filename, 'y','1','0','n','k','2','a','1',str(c_skew),'0','0','2'], polys, verbose = verbose) @@ -744,7 +744,7 @@ def mixed_volume(self, polys, verbose=False): try: return mixed_vol except NameError: - raise RuntimeError, "Mixed volume not found in output; something went wrong running phc." + raise RuntimeError("Mixed volume not found in output; something went wrong running phc.") def start_from(self, start_filename_or_string, polys, input_ring, path_track_file = None, verbose = False): @@ -785,7 +785,7 @@ def start_from(self, start_filename_or_string, polys, input_ring, path_track_fil elif os.path.exists(start_filename_or_string): start_filename = start_filename_or_string else: - raise RuntimeError, "There is something wrong with your start string or filename" + raise RuntimeError("There is something wrong with your start string or filename") # Get the input polynomial text input = self._input_file(polys) @@ -832,7 +832,7 @@ def start_from(self, start_filename_or_string, polys, input_ring, path_track_fil #close down the process: child_phc.close() if not os.path.exists(output_filename): - raise RuntimeError, "The output file does not exist; something went wrong running phc." + raise RuntimeError("The output file does not exist; something went wrong running phc.") # Read the output produced by PHC out = open(output_filename).read() @@ -900,10 +900,10 @@ def blackbox(self, polys, input_ring, verbose = False): print os.system('which phc') + ' PHC needs to be installed and in your path' raise RuntimeError # todo -- why? etc. - raise RuntimeError, open(log_filename).read() + "\nError running phc." + raise RuntimeError(open(log_filename).read() + "\nError running phc.") if not os.path.exists(output_filename): - raise RuntimeError, "The output file does not exist; something went wrong running phc." + raise RuntimeError("The output file does not exist; something went wrong running phc.") # Read the output produced by PHC out = open(output_filename).read() diff --git a/src/sage/interfaces/psage.py b/src/sage/interfaces/psage.py index d3bcfd0215a..af584e69ff3 100644 --- a/src/sage/interfaces/psage.py +++ b/src/sage/interfaces/psage.py @@ -51,7 +51,7 @@ class PSage(Sage): def __init__(self, **kwds): if 'server' in kwds: - raise NotImplementedError, "PSage doesn't work on remote server yet." + raise NotImplementedError("PSage doesn't work on remote server yet.") Sage.__init__(self, **kwds) import sage.misc.misc T = sage.misc.temporary_file.tmp_dir('sage_smp') @@ -138,7 +138,7 @@ def set(self, var, value): def _send_nowait(self, x): if x.find('\n') != -1: - raise ValueError, "x must not have any newlines" + raise ValueError("x must not have any newlines") # Now we want the client Python process to execute two things. # The first is x and the second is c. The effect of c # will be to unlock the lock. diff --git a/src/sage/interfaces/qepcad.py b/src/sage/interfaces/qepcad.py index a8d22e17385..3de9cd97b02 100644 --- a/src/sage/interfaces/qepcad.py +++ b/src/sage/interfaces/qepcad.py @@ -735,7 +735,7 @@ def __init__(self, formula, if isinstance(formula, str): if varlist is None: - raise ValueError, "vars must be specified if formula is a string" + raise ValueError("vars must be specified if formula is a string") free_vars = len(varlist) - formula.count('(') else: @@ -748,9 +748,9 @@ def __init__(self, formula, # Do some error-checking here. Parse the given vars # and ensure they match up with the variables in the formula. if frozenset(varlist) != (fvars | frozenset(fqvars)): - raise ValueError, "specified vars don't match vars in formula" + raise ValueError("specified vars don't match vars in formula") if len(fqvars) and varlist[-len(fqvars):] != fqvars: - raise ValueError, "specified vars don't match quantified vars" + raise ValueError("specified vars don't match quantified vars") free_vars = len(fvars) formula = repr(formula) @@ -759,7 +759,7 @@ def __init__(self, formula, varlist = [v.replace('_', '') for v in varlist] if len(frozenset(varlist)) != len(varlist): - raise ValueError, "variables collide after stripping underscores" + raise ValueError("variables collide after stripping underscores") formula = formula.replace('_', '') qex = Qepcad_expect(logfile=logfile) @@ -812,9 +812,9 @@ def assume(self, assume): if not isinstance(assume, str): assume = qepcad_formula.formula(assume) if len(assume.qvars): - raise ValueError, "assumptions cannot be quantified" + raise ValueError("assumptions cannot be quantified") if not assume.vars.issubset(frozenset(self._varlist[:self._free_vars])): - raise ValueError, "assumption contains variables not present in formula" + raise ValueError("assumption contains variables not present in formula") assume = repr(assume) assume = assume.replace('_', '') result = self._eval_line("assume [%s]" % assume) @@ -868,7 +868,7 @@ def solution_extension(self, kind): y + x > 0 /\ y^2 + x^2 - 3 = 0 """ if kind == 'I': - raise ValueError, "Interactive solution construction not handled by Sage interface" + raise ValueError("Interactive solution construction not handled by Sage interface") result = self._eval_line('solution-extension %s'%kind) tagline = 'An equivalent quantifier-free formula:' loc = result.find(tagline) @@ -947,7 +947,7 @@ def _parse_answer_stats(self): '-----------------------------------------------------------------------------\r\n0 Garbage collections, 0 Cells and 0 Arrays reclaimed, in 0 milliseconds.\r\n492514 Cells in AVAIL, 500000 Cells in SPACE.\r\n\r\nSystem time: 16 milliseconds.\r\nSystem time after the initialization: 4 milliseconds.\r\n-----------------------------------------------------------------------------\r\n' """ if self.phase() != 'EXITED': - raise ValueError, "QEPCAD is not finished yet" + raise ValueError("QEPCAD is not finished yet") final = self._qex.expect().before match = re.search('\nAn equivalent quantifier-free formula:(.*)\n=+ The End =+\r\n\r\n(.*)$', final, re.DOTALL) @@ -1253,7 +1253,7 @@ def __call__(self, *args): args[0] = 'y' if args[0] else 'n' if special == 'interactive': - raise ValueError, "Cannot call %s through Sage interface... interactive commands not handled" + raise ValueError("Cannot call %s through Sage interface... interactive commands not handled") return self._parent._function_call(self._name, args) @@ -1434,7 +1434,7 @@ def qepcad(formula, assume=None, interact=False, solution=None, vars=None, **kwa cells = qe.make_cells(qe.d_true_cells()) qe.quit() if len(cells) == 0: - raise ValueError, "input formula is false everywhere" + raise ValueError("input formula is false everywhere") return cells[0].sample_point_dict() elif solution == 'cell-points': cells = qe.make_cells(qe.d_true_cells()) @@ -1445,10 +1445,10 @@ def qepcad(formula, assume=None, interact=False, solution=None, vars=None, **kwa qe.quit() for c in cells: if c._dimension > 0: - raise ValueError, "input formula is true for infinitely many points" + raise ValueError("input formula is true for infinitely many points") return [c.sample_point_dict() for c in cells] else: - raise ValueError, "Unknown solution type (%s)" % solution + raise ValueError("Unknown solution type (%s)" % solution) import os @@ -1648,7 +1648,7 @@ def _combine_formulas(self, formulas): for f in formulas: vars = vars | f.vars if len(f.qvars): - raise ValueError, "QEPCAD formulas must be in prenex (quantifiers outermost) form" + raise ValueError("QEPCAD formulas must be in prenex (quantifiers outermost) form") return formula_strs, vars def atomic(self, lhs, op='=', rhs=0): @@ -2014,7 +2014,7 @@ def exactly_k(self, k, v, formula, allow_multi=False): from sage.all import ZZ k = ZZ(k) if k < 0: - raise ValueError, "negative k in exactly_k quantifier" + raise ValueError("negative k in exactly_k quantifier") if k == 0: return self.forall(v, self.not_(formula)) @@ -2056,7 +2056,7 @@ def quantifier(self, kind, v, formula, allow_multi=True): form_str = '[' + form_str + ']' v = str(v) if not (v in formula.vars): - raise ValueError, "Attempting to quantify variable which does not occur in formula" + raise ValueError("Attempting to quantify variable which does not occur in formula") form_str = "(%s %s)%s" % (kind, v, form_str) return qformula(form_str, formula.vars - frozenset([v]), [v] + formula.qvars) @@ -2105,7 +2105,7 @@ def _eval_qepcad_algebraic(text): if intv.lower().exact_rational() == lbound and intv.upper().exact_rational() == ubound: return AA.polynomial_root(p, intv) - raise ValueError, "%s or %s not an exact floating-point number"%(lbound, ubound) + raise ValueError("%s or %s not an exact floating-point number"%(lbound, ubound)) class QepcadCell: r""" diff --git a/src/sage/interfaces/qsieve.py b/src/sage/interfaces/qsieve.py index 0f2c1d67dff..93505a88083 100644 --- a/src/sage/interfaces/qsieve.py +++ b/src/sage/interfaces/qsieve.py @@ -68,7 +68,7 @@ def qsieve(n, block=True, time=False, verbose=False): Z = sage.rings.integer.Integer n = Z(n) if len(str(n)) < 40: - raise ValueError, "n must have at least 40 digits" + raise ValueError("n must have at least 40 digits") if block: return qsieve_block(n, time, verbose) else: @@ -211,7 +211,7 @@ def cputime(self): completed or the time is unknown. """ if not self._do_time: - raise ValueError, "you have to start the sieve with the option time=True in order to get timing information" + raise ValueError("you have to start the sieve with the option time=True in order to get timing information") try: return data_to_list(self._get(), self._n, self._do_time)[1] except IndexError: diff --git a/src/sage/interfaces/r.py b/src/sage/interfaces/r.py index 6867e9cdb83..c583dea45fa 100644 --- a/src/sage/interfaces/r.py +++ b/src/sage/interfaces/r.py @@ -361,7 +361,7 @@ def png(self, *args, **kwds): s = self.eval('capabilities("png")') t = r.eval('capabilities("aqua")') if "TRUE" not in s+t: - raise RuntimeError, "R was not compiled with PNG support" + raise RuntimeError("R was not compiled with PNG support") from sage.server.support import EMBEDDED_MODE if EMBEDDED_MODE: @@ -590,7 +590,7 @@ def library(self, library_name): ret = self.eval('require("%s")'%library_name) # try hard to parse the message string in a locale-independent way if ' library(' in ret: # locale-independent key-word - raise ImportError, "%s"%ret + raise ImportError("%s"%ret) else: try: # We need to rebuild keywords! @@ -832,7 +832,7 @@ def set(self, var, value): cmd = '%s <- %s'%(var,value) out = self.eval(cmd) if out.find("error") != -1: - raise TypeError, "Error executing code in R\nCODE:\n\t%s\nR ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in R\nCODE:\n\t%s\nR ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ @@ -1189,7 +1189,7 @@ def __reduce__(self): ... NotImplementedError: pickling of R elements is not yet supported """ - raise NotImplementedError, "pickling of R elements is not yet supported" + raise NotImplementedError("pickling of R elements is not yet supported") def trait_names(self): """ @@ -1849,7 +1849,7 @@ def _latex_(self): try: P.library('Hmisc') except ImportError: - raise RuntimeError, "The R package 'Hmisc' is required for R to LaTeX conversion, but it is not available." + raise RuntimeError("The R package 'Hmisc' is required for R to LaTeX conversion, but it is not available.") return LatexExpr(P.eval('latex(%s, file="");'%self.name())) @@ -1867,7 +1867,7 @@ def __reduce__(self): ... NotImplementedError: pickling of R element methods is not yet supported """ - raise NotImplementedError, "pickling of R element methods is not yet supported" + raise NotImplementedError("pickling of R element methods is not yet supported") def _sage_doc_(self): """ diff --git a/src/sage/interfaces/rubik.py b/src/sage/interfaces/rubik.py index 314c234f474..b7e3f1f2d20 100644 --- a/src/sage/interfaces/rubik.py +++ b/src/sage/interfaces/rubik.py @@ -212,7 +212,7 @@ def solve(self, facets): s = child.after while child.expect(['^5\d+', pexpect.EOF]) == 0: s += child.after - raise ValueError, s + raise ValueError(s) def format_cube(self, facets): colors = sum([[i]*8 for i in range(1,7)], []) @@ -281,10 +281,10 @@ def solve(self, facets, timeout=10, extra_time=2): elif ix == 1: # invalid format child.close(True) - raise ValueError, child.before + raise ValueError(child.before) else: child.close(True) - raise RuntimeError, "timeout" + raise RuntimeError("timeout") def format_cube(self, facets): colors = sum([[i]*8 for i in range(1,7)], []) diff --git a/src/sage/interfaces/sage0.py b/src/sage/interfaces/sage0.py index 589db9cd8d4..57d2e8c777f 100644 --- a/src/sage/interfaces/sage0.py +++ b/src/sage/interfaces/sage0.py @@ -336,7 +336,7 @@ def set(self, var, value): cmd = '%s=%s'%(var,value) out = self.eval(cmd) if 'Traceback' in out: - raise TypeError, "Error executing code in Sage\nCODE:\n\t%s\nSage ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Sage\nCODE:\n\t%s\nSage ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ diff --git a/src/sage/interfaces/scilab.py b/src/sage/interfaces/scilab.py index c19a0c4cb0d..bc4a50870dd 100644 --- a/src/sage/interfaces/scilab.py +++ b/src/sage/interfaces/scilab.py @@ -308,7 +308,7 @@ def set(self, var, value): cmd = '%s=%s;'%(var,value) out = self.eval(cmd) if out.find("error") != -1: - raise TypeError, "Error executing code in Scilab\nCODE:\n\t%s\nScilab ERROR:\n\t%s"%(cmd, out) + raise TypeError("Error executing code in Scilab\nCODE:\n\t%s\nScilab ERROR:\n\t%s"%(cmd, out)) def get(self, var): """ diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py index 58259759aa4..2447fdb3ffc 100644 --- a/src/sage/interfaces/singular.py +++ b/src/sage/interfaces/singular.py @@ -580,7 +580,7 @@ def eval(self, x, allow_semicolon=True, strip=True, **kwds): x = str(x).rstrip().rstrip(';') x = x.replace("> ",">\t") #don't send a prompt (added by Martin Albrecht) if not allow_semicolon and x.find(";") != -1: - raise TypeError, "singular input must not contain any semicolons:\n%s"%x + raise TypeError("singular input must not contain any semicolons:\n%s"%x) if len(x) == 0 or x[len(x) - 1] != ';': x += ';' @@ -832,7 +832,7 @@ def ideal(self, *gens): return self(gens.name(), 'ideal') if not isinstance(gens, (list, tuple)): - raise TypeError, "gens (=%s) must be a list, tuple, string, or Singular element"%gens + raise TypeError("gens (=%s) must be a list, tuple, string, or Singular element"%gens) if len(gens) == 1 and isinstance(gens[0], (list, tuple)): gens = gens[0] @@ -976,7 +976,7 @@ def ring(self, char=0, vars='(x)', order='lp', check=True): if char != 0: n = sage.rings.integer.Integer(char) if not n.is_prime(): - raise ValueError, "the characteristic must be 0 or prime" + raise ValueError("the characteristic must be 0 or prime") R = self('%s,%s,%s'%(char, vars, order), 'ring') self.eval('short=0') # make output include *'s for multiplication for *THIS* ring. return R @@ -1016,7 +1016,7 @@ def set_ring(self, R): // block 2 : ordering C """ if not isinstance(R, SingularElement): - raise TypeError, "R must be a singular ring" + raise TypeError("R must be a singular ring") self.eval("setring %s; short=0"%R.name(), allow_semicolon=True) setring = set_ring @@ -1158,7 +1158,7 @@ def option(self, cmd=None, val=None): return self(self.eval("option(get)"),"intvec") elif cmd == "set": if not isinstance(val,SingularElement): - raise TypeError, "singular.option('set') needs SingularElement as second parameter" + raise TypeError("singular.option('set') needs SingularElement as second parameter") #SingularFunction(self,"option")("\"set\"",val) self.eval("option(set,%s)"%val.name()) else: @@ -1171,7 +1171,7 @@ def _keyboard_interrupt(self): except pexpect.ExceptionPexpect as msg: raise pexcept.ExceptionPexpect("THIS IS A BUG -- PLEASE REPORT. This should never happen.\n" + msg) self._start() - raise KeyboardInterrupt, "Restarting %s (WARNING: all variables defined in previous session are now invalid)"%self + raise KeyboardInterrupt("Restarting %s (WARNING: all variables defined in previous session are now invalid)"%self) class SingularElement(ExpectElement): def __init__(self, parent, type, value, is_name=False): @@ -1359,7 +1359,7 @@ def __setitem__(self, n, value): value = P(value) if isinstance(n, tuple): if len(n) != 2: - raise ValueError, "If n (=%s) is a tuple, it must be a 2-tuple"%n + raise ValueError("If n (=%s) is a tuple, it must be a 2-tuple"%n) x, y = n P.eval('%s[%s,%s] = %s'%(self.name(), x, y, value.name())) else: @@ -1718,7 +1718,7 @@ def sage_poly(self, R=None, kcache=None): return R(sage_repr) else: - raise TypeError, "Cannot coerce %s into %s"%(self,R) + raise TypeError("Cannot coerce %s into %s"%(self,R)) def sage_matrix(self, R, sparse=True): """ @@ -1863,7 +1863,7 @@ def _sage_(self, R=None): R = self.sage_global_ring() br.set_ring() return R - raise NotImplementedError, "Coercion of this datatype not implemented yet" + raise NotImplementedError("Coercion of this datatype not implemented yet") def set_ring(self): """ diff --git a/src/sage/lfunctions/dokchitser.py b/src/sage/lfunctions/dokchitser.py index 4543ec4a565..da6ae492524 100644 --- a/src/sage/lfunctions/dokchitser.py +++ b/src/sage/lfunctions/dokchitser.py @@ -236,14 +236,14 @@ def _gp_eval(self, s): try: t = self.gp().eval(s) except (RuntimeError, TypeError): - raise RuntimeError, "Unable to create L-series, due to precision or other limits in PARI." + raise RuntimeError("Unable to create L-series, due to precision or other limits in PARI.") if '***' in t: - raise RuntimeError, "Unable to create L-series, due to precision or other limits in PARI." + raise RuntimeError("Unable to create L-series, due to precision or other limits in PARI.") return t def __check_init(self): if not self.__init: - raise ValueError, "you must call init_coeffs on the L-function first" + raise ValueError("you must call init_coeffs on the L-function first") def num_coeffs(self, T=1): """ @@ -347,7 +347,7 @@ def init_coeffs(self, v, cutoff=1, self._gp_eval('initLdata("%s",%s,"%s")'%(v,cutoff,w)) return if not isinstance(v, (list, tuple)): - raise TypeError, "v (=%s) must be a list, tuple, or string"%v + raise TypeError("v (=%s) must be a list, tuple, or string"%v) CC = self.__CC v = ','.join([CC(a)._pari_init_() for a in v]) self._gp_eval('Avec = [%s]'%v) @@ -434,7 +434,7 @@ def derivative(self, s, k=1): k = Integer(k) z = self.gp().eval('L(%s,,%s)'%(s,k)) if 'pole' in z: - raise ArithmeticError, z + raise ArithmeticError(z) elif 'Warning' in z: i = z.rfind('\n') msg = z[:i].replace('digits','decimal digits') @@ -492,10 +492,10 @@ def taylor_series(self, a=0, k=6, var='z'): try: z = self.gp()('Vec(Lseries(%s,,%s))'%(a,k-1)) except TypeError as msg: - raise RuntimeError, "%s\nUnable to compute Taylor expansion (try lowering the number of terms)"%msg + raise RuntimeError("%s\nUnable to compute Taylor expansion (try lowering the number of terms)"%msg) r = repr(z) if 'pole' in r: - raise ArithmeticError, r + raise ArithmeticError(r) elif 'Warning' in r: i = r.rfind('\n') msg = r[:i].replace('digits','decimal digits') @@ -584,7 +584,7 @@ def set_coeff_growth(self, coefgrow): 0.0374412812685155 """ if not isinstance(coefgrow, str): - raise TypeError, "coefgrow must be a string" + raise TypeError("coefgrow must be a string") g = self.gp() g.eval('coefgrow(n) = %s'%(coefgrow.replace('\n',' '))) diff --git a/src/sage/lfunctions/lcalc.py b/src/sage/lfunctions/lcalc.py index 5a02aec92bf..b70d39b082b 100644 --- a/src/sage/lfunctions/lcalc.py +++ b/src/sage/lfunctions/lcalc.py @@ -75,7 +75,7 @@ def _compute_L(self, L): if L.base_ring() == sage.rings.all.RationalField(): L = L.minimal_model() return '-e --a1 %s --a2 %s --a3 %s --a4 %s --a6 %s'%tuple(L.a_invariants()) - raise TypeError, "$L$-function of %s not known"%L + raise TypeError("$L$-function of %s not known"%L) def help(self): try: diff --git a/src/sage/lfunctions/sympow.py b/src/sage/lfunctions/sympow.py index f2e553fa280..38f30921fe4 100644 --- a/src/sage/lfunctions/sympow.py +++ b/src/sage/lfunctions/sympow.py @@ -139,16 +139,16 @@ def L(self, E, n, prec): 1.05759924459096 """ if n % 2 == 1: - raise ValueError, "n (=%s) must be even"%n + raise ValueError("n (=%s) must be even"%n) if prec > 64: - raise ValueError, "prec (=%s) must be at most 64"%prec + raise ValueError("prec (=%s) must be at most 64"%prec) if prec < 1: - raise ValueError, "prec (=%s) must be at least 1"%prec + raise ValueError("prec (=%s) must be at least 1"%prec) v = self('-sp %sp%s %s'%(n, prec, self._curve_str(E))) i = v.rfind(': ') if i == -1: print self._fix_err(v) - raise RuntimeError, "failed to compute symmetric power" + raise RuntimeError("failed to compute symmetric power") x = v[i+2:] return x @@ -193,9 +193,9 @@ def Lderivs(self, E, n, prec, d): 1w2: 3.414818600982502E-02 """ if prec > 64: - raise ValueError, "prec (=%s) must be at most 64"%prec + raise ValueError("prec (=%s) must be at most 64"%prec) if prec < 1: - raise ValueError, "prec (=%s) must be at least 1"%prec + raise ValueError("prec (=%s) must be at least 1"%prec) v = self('-sp %sp%sd%s %s'%(n, prec, d, self._curve_str(E))) return self._fix_err(v) @@ -235,7 +235,7 @@ def modular_degree(self, E): i = v.find(s) if i == -1: print self._fix_err(v) - raise RuntimeError, "failed to compute modular degree" + raise RuntimeError("failed to compute modular degree") return sage.rings.all.Integer(v[i+len(s):]) def analytic_rank(self, E): @@ -293,7 +293,7 @@ def analytic_rank(self, E): i = v.rfind(s) if i == -1: print self._fix_err(v) - raise RuntimeError, "failed to compute analytic rank" + raise RuntimeError("failed to compute analytic rank") j = v.rfind(':') r = sage.rings.all.Integer(v[i+len(s):j]) i = v.rfind(' ') diff --git a/src/sage/libs/coxeter3/coxeter_group.py b/src/sage/libs/coxeter3/coxeter_group.py index 3982b6db8c3..c67cd2a7b98 100644 --- a/src/sage/libs/coxeter3/coxeter_group.py +++ b/src/sage/libs/coxeter3/coxeter_group.py @@ -382,7 +382,7 @@ def parabolic_kazhdan_lusztig_polynomial(self, u, v, J, constant_term_one=True): u = self(u) v = self(v) if any(d in J for d in u.descents()) or any(d in J for d in v.descents()): - raise ValueError, "u and v have to be minimal coset representatives" + raise ValueError("u and v have to be minimal coset representatives") P = ZZ['q'] q = P.gen() subgroup = [ z for z in self.weak_order_ideal(lambda x: set(x.descents()).issubset(set(J))) if (u*z).bruhat_le(v) ] @@ -668,7 +668,7 @@ def action_on_rational_function(self, f): n = W.rank() if Q.ngens() != n: - raise ValueError, "the number of generators for the polynomial ring must be the same as the rank of the root system" + raise ValueError("the number of generators for the polynomial ring must be the same as the rank of the root system") basis_elements = [alpha[i] for i in W.index_set()] basis_to_order = dict([(s, i) for i, s in enumerate(W.index_set())]) diff --git a/src/sage/libs/mwrank/interface.py b/src/sage/libs/mwrank/interface.py index bb1c5aeb607..56895acbd34 100644 --- a/src/sage/libs/mwrank/interface.py +++ b/src/sage/libs/mwrank/interface.py @@ -151,7 +151,7 @@ def __init__(self, ainvs, verbose=False): # if not isinstance(ainvs, list) and len(ainvs) <= 5: if not isinstance(ainvs, (list,tuple)) or not len(ainvs) <= 5: - raise TypeError, "ainvs must be a list or tuple of length at most 5." + raise TypeError("ainvs must be a list or tuple of length at most 5.") # Pad ainvs on the beginning by 0's, so e.g. # [a4,a5] works. @@ -161,7 +161,7 @@ def __init__(self, ainvs, verbose=False): try: a_int = [IntegerRing()(x) for x in ainvs] except (TypeError, ValueError): - raise TypeError, "ainvs must be a list or tuple of integers." + raise TypeError("ainvs must be a list or tuple of integers.") self.__ainvs = a_int self.__curve = _Curvedata(a_int[0], a_int[1], a_int[2], a_int[3], a_int[4]) @@ -423,7 +423,7 @@ def two_descent(self, n_aux, second_descent) if not self.__two_descent_data().ok(): - raise RuntimeError, "A 2-descent did not complete successfully." + raise RuntimeError("A 2-descent did not complete successfully.") def __two_descent_data(self): r""" @@ -598,7 +598,7 @@ def regulator(self): """ self.saturate() if not self.certain(): - raise RuntimeError, "Unable to saturate Mordell-Weil group." + raise RuntimeError("Unable to saturate Mordell-Weil group.") R = self.__two_descent_data().regulator() return float(R) @@ -889,7 +889,7 @@ def __init__(self, curve, verbose=True, pp=1, maxr=999): Subgroup of Mordell-Weil group: [] """ if not isinstance(curve, mwrank_EllipticCurve): - raise TypeError, "curve (=%s) must be an mwrank_EllipticCurve"%curve + raise TypeError("curve (=%s) must be an mwrank_EllipticCurve"%curve) self.__curve = curve self.__verbose = verbose self.__pp = pp @@ -1041,11 +1041,11 @@ def process(self, v, sat=0): (True, 1, '[ ]') """ if not isinstance(v, list): - raise TypeError, "v (=%s) must be a list"%v + raise TypeError("v (=%s) must be a list"%v) sat = int(sat) for P in v: if not isinstance(P, (list,tuple)) or len(P) != 3: - raise TypeError, "v (=%s) must be a list of 3-tuples (or 3-element lists) of ints"%v + raise TypeError("v (=%s) must be a list of 3-tuples (or 3-element lists) of ints"%v) self.__mw.process(P, sat) def regulator(self): @@ -1354,7 +1354,7 @@ def search(self, height_limit=18, verbose=False): """ height_limit = float(height_limit) if height_limit >= 21.4: # TODO: docstring says 21.48 (for 32-bit machines; what about 64-bit...?) - raise ValueError, "The height limit must be < 21.4." + raise ValueError("The height limit must be < 21.4.") moduli_option = 0 # Use Stoll's sieving program... see strategies in ratpoints-1.4.c diff --git a/src/sage/libs/pari/gen_py.py b/src/sage/libs/pari/gen_py.py index 1f22aa4127f..8ea4e5dde76 100644 --- a/src/sage/libs/pari/gen_py.py +++ b/src/sage/libs/pari/gen_py.py @@ -239,7 +239,7 @@ def python(z, locals=None): tx = z.real().type() ty = z.imag().type() if tx in ["t_INTMOD", "t_PADIC"] or ty in ["t_INTMOD", "t_PADIC"]: - raise NotImplementedError, "No conversion to python available for t_COMPLEX with t_INTMOD or t_PADIC components" + raise NotImplementedError("No conversion to python available for t_COMPLEX with t_INTMOD or t_PADIC components") if tx == "t_REAL" or ty == "t_REAL": xprec = z.real().precision() # will be 0 if exact yprec = z.imag().precision() # will be 0 if exact @@ -256,7 +256,7 @@ def python(z, locals=None): return QuadraticField(-1,'i')([python(c) for c in list(z)]) if tx == "t_INT" or ty == "t_INT": return QuadraticField(-1,'i').ring_of_integers()([python(c) for c in list(z)]) - raise NotImplementedError, "No conversion to python available for t_COMPLEX with components %s"%(tx,ty) + raise NotImplementedError("No conversion to python available for t_COMPLEX with components %s"%(tx,ty)) elif t == "t_VEC": return [python(x) for x in z.python_list()] elif t == "t_VECSMALL": diff --git a/src/sage/logic/logicparser.py b/src/sage/logic/logicparser.py index 649979827af..2fd92e7005c 100644 --- a/src/sage/logic/logicparser.py +++ b/src/sage/logic/logicparser.py @@ -195,7 +195,7 @@ def tokenize(s): # check to see if '-', '<' or '>' are used incorrectly elif s[i] in '<->': msg = "'%s' can only be used as part of the operators '<->' or '->'." % (s[i]) - raise SyntaxError, msg + raise SyntaxError(msg) if len(tok) > 0: toks.append(tok) i += skip @@ -225,7 +225,7 @@ def tokenize(s): msg = 'invalid variable name ' + tok msg += ": identifiers must begin with a letter and contain only " msg += "alphanumerics and underscores" - raise NameError, msg + raise NameError(msg) toks.append(')') return toks, vars_order diff --git a/src/sage/matrix/benchmark.py b/src/sage/matrix/benchmark.py index 2503d9b0adb..0fe5142f5af 100644 --- a/src/sage/matrix/benchmark.py +++ b/src/sage/matrix/benchmark.py @@ -49,7 +49,7 @@ def report(F, title, systems = ['sage', 'magma'], **kwds): """ import os if len(systems) > 2: - raise NotImplementedError, "at most two systems ('sage' or 'magma')" + raise NotImplementedError("at most two systems ('sage' or 'magma')") print '='*70 print ' '*10 + title print '='*70 @@ -149,7 +149,7 @@ def nullspace_ZZ(n=200, min=0, max=2**32, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def charpoly_ZZ(n=100, min=0, max=9, system='sage'): @@ -188,7 +188,7 @@ def charpoly_ZZ(n=100, min=0, max=9, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def rank_ZZ(n=700, min=0, max=9, system='sage'): @@ -227,7 +227,7 @@ def rank_ZZ(n=700, min=0, max=9, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def rank2_ZZ(n=400, min=0, max=2**64, system='sage'): """ @@ -265,7 +265,7 @@ def rank2_ZZ(n=400, min=0, max=2**64, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) # Smith Form @@ -305,7 +305,7 @@ def smithform_ZZ(n=128, min=0, max=9, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def matrix_multiply_ZZ(n=300, min=-9, max=9, system='sage', times=1): @@ -350,7 +350,7 @@ def matrix_multiply_ZZ(n=300, min=-9, max=9, system='sage', times=1): magma.eval(code) return float(magma.eval('s'))/times else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def matrix_add_ZZ(n=200, min=-9, max=9, system='sage', times=50): """ @@ -396,7 +396,7 @@ def matrix_add_ZZ(n=200, min=-9, max=9, system='sage', times=50): magma.eval(code) return float(magma.eval('s'))/times else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def matrix_add_ZZ_2(n=200, bits=16, system='sage', times=50): """ @@ -456,7 +456,7 @@ def det_ZZ(n=200, min=1, max=100, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def det_QQ(n=300, num_bound=10, den_bound=10, system='sage'): @@ -496,7 +496,7 @@ def det_QQ(n=300, num_bound=10, den_bound=10, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def vecmat_ZZ(n=300, min=-9, max=9, system='sage', times=200): @@ -543,7 +543,7 @@ def vecmat_ZZ(n=300, min=-9, max=9, system='sage', times=200): magma.eval(code) return float(magma.eval('s'))/times else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) @@ -619,7 +619,7 @@ def nullspace_GF(n=300, p=16411, system='sage'): magma.eval(code) return magma.eval('s') else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) # Characteristic Polynomial over GF @@ -658,7 +658,7 @@ def charpoly_GF(n=100, p=16411, system='sage'): magma.eval(code) return magma.eval('s') else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def matrix_add_GF(n=1000, p=16411, system='sage',times=100): """ @@ -699,7 +699,7 @@ def matrix_add_GF(n=1000, p=16411, system='sage',times=100): magma.eval(code) return magma.eval('s') else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) @@ -745,7 +745,7 @@ def matrix_multiply_GF(n=100, p=16411, system='sage', times=3): magma.eval(code) return float(magma.eval('s'))/times else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def rank_GF(n=500, p=16411, system='sage'): @@ -782,7 +782,7 @@ def rank_GF(n=500, p=16411, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def rank2_GF(n=500, p=16411, system='sage'): """ @@ -818,7 +818,7 @@ def rank2_GF(n=500, p=16411, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def det_GF(n=400, p=16411 , system='sage'): """ @@ -855,7 +855,7 @@ def det_GF(n=400, p=16411 , system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) ####################################################################### @@ -917,7 +917,7 @@ def echelon_QQ(n=100, min=0, max=9, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) # Invert a matrix over QQ. @@ -956,7 +956,7 @@ def inverse_QQ(n=100, min=0, max=9, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) # Matrix multiplication over QQ @@ -1002,7 +1002,7 @@ def matrix_multiply_QQ(n=100, bnd=2, system='sage', times=1): magma.eval(code) return float(magma.eval('s'))/times else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) # Determinant of Hilbert matrix @@ -1116,7 +1116,7 @@ def MatrixVector_QQ(n=1000,h=100,system='sage',times=1): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) ####################################################################### @@ -1164,7 +1164,7 @@ def nullspace_RR(n=300, min=0, max=10, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) def nullspace_RDF(n=300, min=0, max=10, system='sage'): @@ -1204,6 +1204,6 @@ def nullspace_RDF(n=300, min=0, max=10, system='sage'): magma.eval(code) return float(magma.eval('s')) else: - raise ValueError, 'unknown system "%s"'%system + raise ValueError('unknown system "%s"'%system) diff --git a/src/sage/matrix/berlekamp_massey.py b/src/sage/matrix/berlekamp_massey.py index 751d7df6ca1..e6314ee9a39 100644 --- a/src/sage/matrix/berlekamp_massey.py +++ b/src/sage/matrix/berlekamp_massey.py @@ -64,9 +64,9 @@ def berlekamp_massey(a): """ if not isinstance(a, list): - raise TypeError, "Argument 1 must be a list." + raise TypeError("Argument 1 must be a list.") if len(a)%2 != 0: - raise ValueError, "Argument 1 must have an even number of terms." + raise ValueError("Argument 1 must have an even number of terms.") M = len(a)//2 diff --git a/src/sage/matrix/constructor.py b/src/sage/matrix/constructor.py index 657f0b2d28b..328dbe2e532 100644 --- a/src/sage/matrix/constructor.py +++ b/src/sage/matrix/constructor.py @@ -547,7 +547,7 @@ def _matrix_constructor(*args, **kwds): if len(args) >= 1 and is_Ring(args[0]): # A ring is specified if kwds.get('ring', args[0]) != args[0]: - raise ValueError, "Specified rings are not the same" + raise ValueError("Specified rings are not the same") else: ring = args[0] args.pop(0) @@ -563,7 +563,7 @@ def _matrix_constructor(*args, **kwds): nrows = int(args[0]) args.pop(0) if kwds.get('nrows', nrows) != nrows: - raise ValueError, "Number of rows specified in two places and they are not the same" + raise ValueError("Number of rows specified in two places and they are not the same") except TypeError: nrows = kwds.get('nrows', None) else: @@ -578,7 +578,7 @@ def _matrix_constructor(*args, **kwds): ncols = int(args[0]) args.pop(0) if kwds.get('ncols', ncols) != ncols: - raise ValueError, "Number of columns specified in two places and they are not the same" + raise ValueError("Number of columns specified in two places and they are not the same") except TypeError: ncols = kwds.get('ncols', None) else: @@ -597,7 +597,7 @@ def _matrix_constructor(*args, **kwds): elif len(args) == 1: if isinstance(args[0], (types.FunctionType, types.LambdaType, types.MethodType)): if ncols is None and nrows is None: - raise ValueError, "When passing in a callable, the dimensions of the matrix must be specified" + raise ValueError("When passing in a callable, the dimensions of the matrix must be specified") if ncols is None: ncols = nrows elif nrows is None: @@ -615,16 +615,16 @@ def _matrix_constructor(*args, **kwds): # Ensure we have a list of lists, each inner list having the same number of elements first_len = len(args[0][0]) if not all( (isinstance(v, (list, tuple)) or is_Vector(v)) and len(v) == first_len for v in args[0]): - raise ValueError, "List of rows is not valid (rows are wrong types or lengths)" + raise ValueError("List of rows is not valid (rows are wrong types or lengths)") # We have a list of rows or vectors if nrows is None: nrows = len(args[0]) elif nrows != len(args[0]): - raise ValueError, "Number of rows does not match up with specified number." + raise ValueError("Number of rows does not match up with specified number.") if ncols is None: ncols = len(args[0][0]) elif ncols != len(args[0][0]): - raise ValueError, "Number of columns does not match up with specified number." + raise ValueError("Number of columns does not match up with specified number.") entries = [] for v in args[0]: @@ -639,9 +639,9 @@ def _matrix_constructor(*args, **kwds): if ncols is None: ncols = len(args[0]) // nrows elif ncols != len(args[0]) // nrows: - raise ValueError, "entries has the wrong length" + raise ValueError("entries has the wrong length") elif len(args[0]) > 0: - raise ValueError, "entries has the wrong length" + raise ValueError("entries has the wrong length") entries = args[0] @@ -710,9 +710,9 @@ def _matrix_constructor(*args, **kwds): entry_ring = args[0].parent() entries = args[0] else: - raise ValueError, "Invalid matrix constructor. Type matrix? for help" + raise ValueError("Invalid matrix constructor. Type matrix? for help") else: - raise ValueError, "Invalid matrix constructor. Type matrix? for help" + raise ValueError("Invalid matrix constructor. Type matrix? for help") if nrows is None: nrows = 0 @@ -804,7 +804,7 @@ def prepare(w): elif ring is complex: ring = rings.CDF elif not is_Ring(ring): - raise TypeError, "unable to find a common ring for all elements" + raise TypeError("unable to find a common ring for all elements") return entries, ring def prepare_dict(w): diff --git a/src/sage/matrix/matrix_integer_dense_saturation.py b/src/sage/matrix/matrix_integer_dense_saturation.py index 08e42b76e15..1134fa22308 100644 --- a/src/sage/matrix/matrix_integer_dense_saturation.py +++ b/src/sage/matrix/matrix_integer_dense_saturation.py @@ -80,7 +80,7 @@ def random_sublist_of_size(k, n): [0, 1, 3, 4, 5, 7, 8] """ if n > k: - raise ValueError, "n must be <= len(v)" + raise ValueError("n must be <= len(v)") if n == k: return range(k) if n >= k//2+5: diff --git a/src/sage/matrix/symplectic_basis.py b/src/sage/matrix/symplectic_basis.py index a5e2d437b65..a84dc0eecb5 100644 --- a/src/sage/matrix/symplectic_basis.py +++ b/src/sage/matrix/symplectic_basis.py @@ -252,17 +252,17 @@ def symplectic_basis_over_field(M): Full MatrixSpace of 8 by 8 dense matrices over Real Field with 53 bits of precision """ if not M.base_ring().is_field(): - raise ValueError, "Can only find symplectic bases for matrices over fields" + raise ValueError("Can only find symplectic bases for matrices over fields") if not M.is_square(): - raise ValueError, "Can only find symplectic bases for square matrices" + raise ValueError("Can only find symplectic bases for square matrices") if not M.transpose() + M == 0: - raise ValueError, "Can only find symplectic bases for anti-symmetric matrices" + raise ValueError("Can only find symplectic bases for anti-symmetric matrices") E = M.__copy__() n = E.nrows() for i in range(n): if not E[i, i].is_zero(): - raise ValueError, "Can only find symplectic bases for alternating matrices" + raise ValueError("Can only find symplectic bases for alternating matrices") B = E.parent().one().__copy__() zeroes = [] @@ -456,15 +456,15 @@ def symplectic_basis_over_ZZ(M): Full MatrixSpace of 5 by 5 dense matrices over Integer Ring """ if not M.is_square(): - raise ValueError, "Can only find symplectic bases for square matrices" + raise ValueError("Can only find symplectic bases for square matrices") if not M.transpose() + M == 0: - raise ValueError, "Can only find symplectic bases for anti-symmetric matrices" + raise ValueError("Can only find symplectic bases for anti-symmetric matrices") E = M.__copy__().change_ring(ZZ) n = E.nrows() for i in range(n): if not E[i, i].is_zero(): - raise ValueError, "Can only find symplectic bases for alternating matrices" + raise ValueError("Can only find symplectic bases for alternating matrices") B = E.parent().one().__copy__() zeroes = [] diff --git a/src/sage/media/wav.py b/src/sage/media/wav.py index e4d30c77810..cd41b286f60 100644 --- a/src/sage/media/wav.py +++ b/src/sage/media/wav.py @@ -84,9 +84,9 @@ def __init__(self, data=None, **kwds): self._bytes = kwds['bytes'] self._channel_data = kwds['channel_data'] except KeyError as msg: - raise KeyError, msg + " invalid input to Wave initializer" + raise KeyError(msg + " invalid input to Wave initializer") else: - raise ValueError, "Must give a filename" + raise ValueError("Must give a filename") def save(self, filename='sage.wav'): @@ -245,7 +245,7 @@ def set_values(self, values, channel=0): c = self.channel_data(channel) npoints = len(c) if len(values) != npoints: - raise ValueError, "values (of length %s) must have length %s"%(len(values), npoints) + raise ValueError("values (of length %s) must have length %s"%(len(values), npoints)) # unscale the values scale = float(1 << (8*self._width -1)) @@ -367,7 +367,7 @@ def convolve(self, right, channel=0): inverse fft back. """ if not isinstance(right, Wave): - raise TypeError, "right must be a wave" + raise TypeError("right must be a wave") npoints = self._nframes v = self.vector(npoints, channel=channel).fft() w = right.vector(npoints, channel=channel).fft() diff --git a/src/sage/misc/benchmark.py b/src/sage/misc/benchmark.py index 62b936d9aa6..e8d16e886f6 100644 --- a/src/sage/misc/benchmark.py +++ b/src/sage/misc/benchmark.py @@ -56,7 +56,7 @@ def benchmark(n=-1): try: desc, t = eval("bench%s()"%n) except NameError: - raise RuntimeError, "no benchmark %s"%n + raise RuntimeError("no benchmark %s"%n) print desc print "Time: %s seconds"%t return (n, t, desc) diff --git a/src/sage/misc/cython.py b/src/sage/misc/cython.py index 4afc9046c5c..84215ec55f8 100644 --- a/src/sage/misc/cython.py +++ b/src/sage/misc/cython.py @@ -490,7 +490,7 @@ def cython(filename, verbose=False, compile_message=False, if os.system(cmd): log = open('%s/log'%build_dir).read() err = subtract_from_line_numbers(open('%s/err'%build_dir).read(), offset) - raise RuntimeError, "Error converting %s to C:\n%s\n%s"%(filename, log, err) + raise RuntimeError("Error converting %s to C:\n%s\n%s"%(filename, log, err)) if language=='c++': os.system("cd '%s' && mv '%s.c' '%s.cpp'"%(build_dir,name,name)) @@ -533,14 +533,14 @@ def cython(filename, verbose=False, compile_message=False, if os.system(cmd): log = open('%s/log'%build_dir).read() err = open('%s/err'%build_dir).read() - raise RuntimeError, "Error compiling %s:\n%s\n%s"%(filename, log, err) + raise RuntimeError("Error compiling %s:\n%s\n%s"%(filename, log, err)) # Move from lib directory. cmd = 'mv %s/build/lib.*/* %s'%(build_dir, build_dir) if verbose: print(cmd) if os.system(cmd): - raise RuntimeError, "Error copying extension module for %s"%filename + raise RuntimeError("Error copying extension module for %s"%filename) if create_local_so_file: # Copy from lib directory into local directory @@ -550,7 +550,7 @@ def cython(filename, verbose=False, compile_message=False, libext = 'dll' cmd = 'cp %s/%s.%s %s'%(build_dir, name, libext, os.path.abspath(os.curdir)) if os.system(cmd): - raise RuntimeError, "Error making local copy of shared object library for %s"%filename + raise RuntimeError("Error making local copy of shared object library for %s"%filename) return name, build_dir diff --git a/src/sage/misc/edit_module.py b/src/sage/misc/edit_module.py index 9e8f8ece06e..19ecf93888b 100644 --- a/src/sage/misc/edit_module.py +++ b/src/sage/misc/edit_module.py @@ -178,7 +178,7 @@ def set_edit_template(template_string): template_string = Template(template_string) fields = set(template_fields(template_string)) if not(fields <= set(['file','line']) and ('file' in fields)): - raise ValueError, "Only ${file} and ${line} are allowed as template variables, and ${file} must occur." + raise ValueError("Only ${file} and ${line} are allowed as template variables, and ${file} must occur.") edit_template = template_string ## The routine set_editor is for convenience and hence is allowed to apply magic. Given an editor name @@ -209,7 +209,7 @@ def set_editor(editor_name,opts=''): if editor_name in sage.misc.edit_module.template_defaults: set_edit_template(Template(template_defaults[editor_name].safe_substitute(opts=opts))) else: - raise ValueError, "editor_name not known. Try set_edit_template() instead." + raise ValueError("editor_name not known. Try set_edit_template() instead.") def edit(obj, editor=None, bg=None): r"""nodetex @@ -265,10 +265,10 @@ def edit(obj, editor=None, bg=None): opts = ' '.join(EDITOR[1:]) #for future use set_editor(base,opts=opts) except (ValueError, KeyError, IndexError): - raise ValueError, "Use set_edit_template() to set a default" + raise ValueError("Use set_edit_template() to set a default") if not(edit_template): - raise ValueError, "Use set_edit_template() to set a default" + raise ValueError("Use set_edit_template() to set a default") filename, lineno = file_and_line(obj) cmd = edit_template.substitute(line = lineno, file = filename) diff --git a/src/sage/misc/explain_pickle.py b/src/sage/misc/explain_pickle.py index ad371205c82..fe821c1c98f 100644 --- a/src/sage/misc/explain_pickle.py +++ b/src/sage/misc/explain_pickle.py @@ -237,7 +237,7 @@ def explain_pickle(pickle=None, file=None, compress=True, **kwargs): elif file is not None: p = open(file).read() else: - raise ValueError, "Either pickle or file must be specified" + raise ValueError("Either pickle or file must be specified") if compress: try: @@ -278,7 +278,7 @@ def explain_pickle_string(pickle, in_current_sage=False, if eval: if default_assumptions: - raise ValueError, "Not safe to evaluate code generated with default_assumptions" + raise ValueError("Not safe to evaluate code generated with default_assumptions") from sage.misc.sage_eval import sage_eval result = sage_eval(ans, preparse=preparse) print ans @@ -430,7 +430,7 @@ def __init__(self, sib, in_current_sage=False, default_assumptions=False, self.stack = [] self.memo = {} if in_current_sage and default_assumptions: - raise ValueError, "in_current_sage and default_assumptions must not both be true" + raise ValueError("in_current_sage and default_assumptions must not both be true") self.new_instance = self.sib.import_name('types', 'InstanceType') @@ -455,7 +455,7 @@ def run_pickle(self, p): try: handler = getattr(self, op.name) except AttributeError: - raise NotImplementedError, 'PickleExplainer does not yet handle opcode %s' % op.name + raise NotImplementedError('PickleExplainer does not yet handle opcode %s' % op.name) if arg is None: handler() else: @@ -1825,7 +1825,7 @@ def PROTO(self, proto): result: 0 """ if not 0 <= proto <= 2: - raise ValueError, "unsupported pickle protocol: %d" % proto + raise ValueError("unsupported pickle protocol: %d" % proto) def PUT(self, n): r""" diff --git a/src/sage/misc/functional.py b/src/sage/misc/functional.py index b049dbfe635..71cb5777a02 100644 --- a/src/sage/misc/functional.py +++ b/src/sage/misc/functional.py @@ -195,7 +195,7 @@ def characteristic_polynomial(x, var='x'): try: return x.charpoly(var) except AttributeError: - raise NotImplementedError, "computation of charpoly of x (=%s) not implemented"%x + raise NotImplementedError("computation of charpoly of x (=%s) not implemented"%x) charpoly = characteristic_polynomial @@ -990,7 +990,7 @@ def lift(x): try: return x.lift() except AttributeError: - raise ArithmeticError, "no lift defined." + raise ArithmeticError("no lift defined.") def log(x,b=None): r""" diff --git a/src/sage/misc/misc.py b/src/sage/misc/misc.py index 529f5c3ddd6..a0c3951f32c 100644 --- a/src/sage/misc/misc.py +++ b/src/sage/misc/misc.py @@ -461,7 +461,7 @@ def verbose(mesg="", t=0, level=1, caller_name=None): def todo(mesg=""): caller_name = sys._getframe(1).f_code.co_name - raise NotImplementedError, "%s: todo -- %s"%(caller_name, mesg) + raise NotImplementedError("%s: todo -- %s"%(caller_name, mesg)) def set_verbose(level, files='all'): """ @@ -888,7 +888,7 @@ def newton_method_sizes(N): N = int(N) if N < 1: - raise ValueError, "N (=%s) must be a positive integer" % N + raise ValueError("N (=%s) must be a positive integer" % N) output = [] while N > 1: @@ -997,7 +997,7 @@ def self_compose(f, n): typecheck(n, (int, long, Integer), 'n') if n < 0: - raise ValueError, "n must be a nonnegative integer, not %s." % n + raise ValueError("n must be a nonnegative integer, not %s." % n) return lambda x: nest(f, n, x) @@ -1042,7 +1042,7 @@ def nest(f, n, x): typecheck(n, (int, long, Integer), 'n') if n < 0: - raise ValueError, "n must be a nonnegative integer, not %s." % n + raise ValueError("n must be a nonnegative integer, not %s." % n) for i in xrange(n): x = f(x) @@ -1192,7 +1192,7 @@ def srange(start, end=None, step=1, universe=None, check=True, include_endpoint= start, end, step = universe(start), universe(end), universe(step) if step == Sequence([step]).universe()(0): - raise ValueError, "srange() step argument must not be zero" + raise ValueError("srange() step argument must not be zero") if universe in [int, long, ZZ]: if include_endpoint and (end-start) % step == 0: @@ -1287,7 +1287,7 @@ def xsrange(start, end=None, step=1, universe=None, check=True, include_endpoint start, end, step = universe(start), universe(end), universe(step) if step == Sequence([step]).universe()(0): - raise ValueError, "xsrange() step argument must not be zero" + raise ValueError("xsrange() step argument must not be zero") if universe in [int, long, ZZ]: if include_endpoint and (end-start) % step == 0: @@ -1427,7 +1427,7 @@ def ellipsis_range(*args, **kwds): skip = False elif args[i] is Ellipsis: if len(args) == i+1: - raise IndexError, "Ellipsis range must have an endpoint, use (n..) for infinite sequence." + raise IndexError("Ellipsis range must have an endpoint, use (n..) for infinite sequence.") start, end = args[i-1], args[i+1] if i < 2 or args[i-2] is not Ellipsis: L.pop() @@ -1756,7 +1756,7 @@ def typecheck(x, C, var="x"): error message. """ if not isinstance(x, C): - raise TypeError, "%s (=%s) must be of type %s."%(var,x,C) + raise TypeError("%s (=%s) must be of type %s."%(var,x,C)) ################################################################# # This will likely eventually be useful. diff --git a/src/sage/misc/package.py b/src/sage/misc/package.py index de94d8b3c15..590b8550e2f 100644 --- a/src/sage/misc/package.py +++ b/src/sage/misc/package.py @@ -164,12 +164,12 @@ def install_package(package=None, force=False): print "Possible names of non-installed packages starting with '%s':"%(package) for P in L: print " ", P - raise ValueError, "There is more than one package name starting with '%s'. Please specify!"%(package) + raise ValueError("There is more than one package name starting with '%s'. Please specify!"%(package)) if len(L)==0: if not force: if is_package_installed(package): - raise ValueError, "Package is already installed. Try install_package('%s',force=True)"%(package) - raise ValueError, "There is no package name starting with '%s'."%(package) + raise ValueError("Package is already installed. Try install_package('%s',force=True)"%(package)) + raise ValueError("There is no package name starting with '%s'."%(package)) # len(L)==1, i.e. exactly one package matches the given one. os.system('sage -f "%s"'%(L[0])) __installed_packages = None diff --git a/src/sage/misc/preparser.py b/src/sage/misc/preparser.py index 431b735fa13..e018d841c7b 100644 --- a/src/sage/misc/preparser.py +++ b/src/sage/misc/preparser.py @@ -448,7 +448,7 @@ def containing_block(code, ix, delimiters=['()','[]','{}'], require_delim=True): start -= 1 if start == -1: if require_delim: - raise SyntaxError, "Unbalanced or missing ()'s" + raise SyntaxError("Unbalanced or missing ()'s") else: break if code[start] in openings: @@ -466,7 +466,7 @@ def containing_block(code, ix, delimiters=['()','[]','{}'], require_delim=True): while end < len(code): end += 1 if end == len(code): - raise SyntaxError, "Unbalanced or missing ()'s" + raise SyntaxError("Unbalanced or missing ()'s") if code[end] == openings[p]: level += 1 elif code[end] == closings[p]: @@ -503,7 +503,7 @@ def parse_ellipsis(code, preparse_step=True): ix = code.find('..') while ix != -1: if ix == 0: - raise SyntaxError, "Cannot start line with ellipsis." + raise SyntaxError("Cannot start line with ellipsis.") elif code[ix-1]=='.': # '...' be valid Python in index slices code = code[:ix-1] + "Ellipsis" + code[ix+2:] diff --git a/src/sage/misc/sage_eval.py b/src/sage/misc/sage_eval.py index 36bc4e4b1ef..9049344283c 100644 --- a/src/sage/misc/sage_eval.py +++ b/src/sage/misc/sage_eval.py @@ -178,7 +178,7 @@ def sage_eval(source, locals=None, cmds='', preparse=True): source = source[1] if not isinstance(source, basestring): - raise TypeError, "source must be a string." + raise TypeError("source must be a string.") if locals is None: locals = {} diff --git a/src/sage/misc/sage_extension.py b/src/sage/misc/sage_extension.py index 33ad065184c..076e945c48a 100644 --- a/src/sage/misc/sage_extension.py +++ b/src/sage/misc/sage_extension.py @@ -146,7 +146,7 @@ def iload(self, s): try: F = open(name) except IOError: - raise ImportError, 'could not open file "%s"'%name + raise ImportError('could not open file "%s"'%name) shell = self.shell diff --git a/src/sage/misc/sage_input.py b/src/sage/misc/sage_input.py index 54a624ab446..29edeacb9e8 100644 --- a/src/sage/misc/sage_input.py +++ b/src/sage/misc/sage_input.py @@ -539,7 +539,7 @@ def __call__(self, x, coerced=False): self._locals[loc_name] = x return SIE_literal_stringrep(self, loc_name) else: - raise ValueError, "Can't convert %r to sage_input form"%x + raise ValueError("Can't convert %r to sage_input form"%x) def preparse(self): r""" @@ -1009,12 +1009,12 @@ def gen(self, parent, n=0): if not parent in self._parent_gens: self(parent) if not parent in self._parent_gens: - raise ValueError, "%s did not register generators for sage_input" % parent + raise ValueError("%s did not register generators for sage_input" % parent) gens = self._parent_gens[parent] if n > len(gens): - raise ValueError, "%s registered only %d generators for sage_input" % (parent, len(gens)) + raise ValueError("%s registered only %d generators for sage_input" % (parent, len(gens))) return gens[n] @@ -2372,7 +2372,7 @@ def _sie_format(self, sif): fop = ' - ' prec = _prec_addsub else: - raise ValueError, 'Unhandled op %s in SIE_binary' % op + raise ValueError('Unhandled op %s in SIE_binary' % op) lhs = sif.format(self._sie_operands[0], prec) rhs = sif.format(self._sie_operands[1], prec+1) @@ -2494,7 +2494,7 @@ def _sie_format(self, sif): elif op == '~': prec = _prec_bitnot else: - raise ValueError, 'Unhandled op %s in SIE_unary' % op + raise ValueError('Unhandled op %s in SIE_unary' % op) if rprec is None: rprec = prec @@ -3086,7 +3086,7 @@ def _sie_format(self, sif): ... ValueError: Cannot format SIE_assign as expression """ - raise ValueError, "Cannot format SIE_assign as expression" + raise ValueError("Cannot format SIE_assign as expression") def _sie_format_statement(self, sif): r""" diff --git a/src/sage/misc/sage_itertools.py b/src/sage/misc/sage_itertools.py index eb2cdd11a0d..93177dbd06c 100644 --- a/src/sage/misc/sage_itertools.py +++ b/src/sage/misc/sage_itertools.py @@ -79,7 +79,7 @@ def min_cmp(L, cmp=None): try: m = iterator.next() except StopIteration: - raise ValueError, "min_cmp() arg is an empty sequence" + raise ValueError("min_cmp() arg is an empty sequence") for item in iterator: if cmp(item, m) < 0: m = item @@ -134,7 +134,7 @@ def max_cmp(L, cmp=None): try: m = iterator.next() except StopIteration: - raise ValueError, "max_cmp() arg is an empty sequence" + raise ValueError("max_cmp() arg is an empty sequence") for item in iterator: if cmp(item, m) > 0: m = item diff --git a/src/sage/misc/sagedoc.py b/src/sage/misc/sagedoc.py index 644152272e8..e7fa95ebe62 100644 --- a/src/sage/misc/sagedoc.py +++ b/src/sage/misc/sagedoc.py @@ -488,7 +488,7 @@ def format(s, embedded=False): """ if not isinstance(s, str): - raise TypeError, "s must be a string" + raise TypeError("s must be a string") # Doc strings may contain embedding information, which should not # be subject to formatting (line breaks must not be inserted). @@ -587,7 +587,7 @@ def format_src(s): 'Sq(*nums):' """ if not isinstance(s, str): - raise TypeError, "s must be a string" + raise TypeError("s must be a string") docs = set([]) import sage.all while True: @@ -1351,7 +1351,7 @@ def __call__(self, obj, output='html', view=True): from sagenb.misc.sphinxify import sphinxify return sphinxify(s, format='text') else: - raise ValueError, "output type %s not recognized" % output + raise ValueError("output type %s not recognized" % output) def _open(self, name, testing=False): """ @@ -1377,8 +1377,8 @@ def _open(self, name, testing=False): url = self._base_url + os.path.join(name, "index.html") path = os.path.join(self._base_path, name, "index.html") if not os.path.exists(path): - raise OSError, """The document '%s' does not exist. Please build it -with 'sage -docbuild %s html --mathjax' and try again.""" %(name, name) + raise OSError("""The document '%s' does not exist. Please build it +with 'sage -docbuild %s html --mathjax' and try again.""" %(name, name)) if testing: return (url, path) diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py index bf37acae44d..7acaa6f04ce 100644 --- a/src/sage/misc/sageinspect.py +++ b/src/sage/misc/sageinspect.py @@ -282,7 +282,7 @@ def _extract_source(lines, lineno): [' class f():\n', ' pass\n'] """ if lineno < 1: - raise ValueError, "Line numbering starts at 1! (tried to extract line %s)" % lineno + raise ValueError("Line numbering starts at 1! (tried to extract line %s)" % lineno) lineno -= 1 if isinstance(lines, str): @@ -1284,7 +1284,7 @@ def foo(x, a='\')"', b={not (2+1==3):'bar'}): return source = sage_getsource(obj) return inspect.ArgSpec(*_sage_getargspec_cython(source)) if not callable(obj): - raise TypeError, "obj is not a code object" + raise TypeError("obj is not a code object") try: return inspect.ArgSpec(*obj._sage_argspec_()) except (AttributeError, TypeError): @@ -1590,7 +1590,7 @@ class ParentMethods: if B is None: raise AttributeError except AttributeError: - raise IOError, "could not get source code" + raise IOError("could not get source code") return sage_getsourcelines(B) # M should just be the top-most module. # Hence, normally it is just 'sage' @@ -1603,7 +1603,7 @@ class ParentMethods: if B is None: raise AttributeError except AttributeError: - raise IOError, "could not get source code" + raise IOError("could not get source code") return sage_getsourcelines(B) lines, base_lineno = sage_getsourcelines(M) diff --git a/src/sage/misc/superseded.py b/src/sage/misc/superseded.py index 968897a0591..43454f45256 100644 --- a/src/sage/misc/superseded.py +++ b/src/sage/misc/superseded.py @@ -182,7 +182,7 @@ def is_class(gc_ref): for key, val in ref_copy.iteritems(): if val is self: return key - raise AttributeError, "The name of this deprecated function can not be determined" + raise AttributeError("The name of this deprecated function can not be determined") def __call__(self, *args, **kwds): """ diff --git a/src/sage/misc/trace.py b/src/sage/misc/trace.py index 0e6e88597b9..b53b8f65d72 100644 --- a/src/sage/misc/trace.py +++ b/src/sage/misc/trace.py @@ -73,7 +73,7 @@ def trace(code, preparse=True): """ from sage.plot.plot import EMBEDDED_MODE if EMBEDDED_MODE: - raise NotImplementedError, "the trace command is not implemented in the Sage notebook; you must use the command line." + raise NotImplementedError("the trace command is not implemented in the Sage notebook; you must use the command line.") from IPython.core.debugger import Pdb pdb = Pdb() diff --git a/src/sage/misc/unknown.py b/src/sage/misc/unknown.py index 1f6eb76400f..ac947a6afa6 100644 --- a/src/sage/misc/unknown.py +++ b/src/sage/misc/unknown.py @@ -151,6 +151,6 @@ def __cmp__(self, other): if other: return -1 else: return +1 else: - raise ValueError, "Unable to compare %s with %s"%(self, other) + raise ValueError("Unable to compare %s with %s"%(self, other)) Unknown = UnknownClass() diff --git a/src/sage/misc/viewer.py b/src/sage/misc/viewer.py index 8bcbb4824c9..9df57539f44 100644 --- a/src/sage/misc/viewer.py +++ b/src/sage/misc/viewer.py @@ -133,7 +133,7 @@ def default_viewer(viewer=None): elif viewer.startswith('pdf'): return PDF_VIEWER else: - raise ValueError, 'Unknown type of viewer: %s.' % viewer + raise ValueError('Unknown type of viewer: %s.' % viewer) from sage.structure.sage_object import SageObject @@ -177,7 +177,7 @@ def _set(self, app=None, TYPE='browser'): """ TYPE = TYPE.lower() if TYPE not in VIEWERS: - raise ValueError, 'Unrecognized type of viewer: %s' % TYPE + raise ValueError('Unrecognized type of viewer: %s' % TYPE) if app is None: try: return _viewer_prefs[TYPE] diff --git a/src/sage/modular/abvar/abvar.py b/src/sage/modular/abvar/abvar.py index 3a7f23431c4..d705978ddf2 100644 --- a/src/sage/modular/abvar/abvar.py +++ b/src/sage/modular/abvar/abvar.py @@ -135,10 +135,10 @@ def __init__(self, groups, base_field, is_simple=None, newform_level=None, """ if check: if not isinstance(groups, tuple): - raise TypeError, "groups must be a tuple" + raise TypeError("groups must be a tuple") for G in groups: if not is_CongruenceSubgroup(G): - raise TypeError, "each element of groups must be a congruence subgroup" + raise TypeError("each element of groups must be a congruence subgroup") self.__groups = groups if is_simple is not None: self.__is_simple = is_simple @@ -149,7 +149,7 @@ def __init__(self, groups, base_field, is_simple=None, newform_level=None, if isogeny_number is not None: self.__isogeny_number = isogeny_number if check and not is_Ring(base_field) and base_field.is_field(): - raise TypeError, "base_field must be a field" + raise TypeError("base_field must be a field") ParentWithBase.__init__(self, base_field, category = ModularAbelianVarieties(base_field)) def groups(self): @@ -190,7 +190,7 @@ def lattice(self): ... NotImplementedError: BUG -- lattice method must be defined in derived class """ - raise NotImplementedError, "BUG -- lattice method must be defined in derived class" + raise NotImplementedError("BUG -- lattice method must be defined in derived class") ############################################################################# def free_module(self): @@ -501,7 +501,7 @@ def _isogeny_to_newform_abelian_variety(self): pass if not self.is_simple(): - raise ValueError, "self is not simple" + raise ValueError("self is not simple") ls = [] @@ -556,23 +556,23 @@ def _simple_isogeny(self, other): NotImplementedError: _simple_isogeny only implemented when both abelian variety have the same ambient product Jacobian """ if not is_ModularAbelianVariety(other): - raise TypeError, "other must be a modular abelian variety" + raise TypeError("other must be a modular abelian variety") if not self.is_simple(): - raise ValueError, "self is not simple" + raise ValueError("self is not simple") if not other.is_simple(): - raise ValueError, "other is not simple" + raise ValueError("other is not simple") if self.groups() != other.groups(): # The issue here is that the stuff below probably won't make any sense at all if we don't know # that the two newform abelian varieties $A_f$ are identical. - raise NotImplementedError, "_simple_isogeny only implemented when both abelian variety have the same ambient product Jacobian" + raise NotImplementedError("_simple_isogeny only implemented when both abelian variety have the same ambient product Jacobian") if (self.newform_level() != other.newform_level()) or \ (self.isogeny_number() != other.isogeny_number()): - raise ValueError, "self and other do not correspond to the same newform" + raise ValueError("self and other do not correspond to the same newform") return other._isogeny_to_newform_abelian_variety().complementary_isogeny() * \ self._isogeny_to_newform_abelian_variety() @@ -602,7 +602,7 @@ def _Hom_(self, B, cat=None): F = QQbar else: # TODO -- improve this - raise ValueError, "please specify a category" + raise ValueError("please specify a category") cat = ModularAbelianVarieties(F) if self is B: return self.endomorphism_ring(cat) @@ -735,7 +735,7 @@ def intersection(self, other): # at least that the ambient Jacobian product is the same for # them. if not self.in_same_ambient_variety(other): - raise TypeError, "other must be an abelian variety in the same ambient space" + raise TypeError("other must be an abelian variety in the same ambient space") # 1. Compute the abelian variety (connected) part of the intersection V = self.vector_space().intersection(other.vector_space()) @@ -847,9 +847,9 @@ def __add__(self, other): if not is_ModularAbelianVariety(other): if other == 0: return self - raise TypeError, "other must be a modular abelian variety" + raise TypeError("other must be a modular abelian variety") if self.groups() != other.groups(): - raise ValueError, "incompatible ambient Jacobians" + raise ValueError("incompatible ambient Jacobians") L = self.vector_space() + other.vector_space() M = L.intersection(self._ambient_lattice()) return ModularAbelianVariety(self.groups(), M, self.base_field(), check=False) @@ -906,7 +906,7 @@ def __pow__(self, n): """ n = ZZ(n) if n < 0: - raise ValueError, "n must be nonnegative" + raise ValueError("n must be nonnegative") if n == 0: return self.zero_subvariety() if n == 1: @@ -934,9 +934,9 @@ def __mul__(self, other): Abelian subvariety of dimension 4 of J0(65) x J0(65) x J0(11) """ if not is_ModularAbelianVariety(other): - raise TypeError, "other must be a modular abelian variety" + raise TypeError("other must be a modular abelian variety") if other.base_ring() != self.base_ring(): - raise TypeError, "self and other must have the same base ring" + raise TypeError("self and other must have the same base ring") groups = tuple(list(self.groups()) + list(other.groups())) lattice = self.lattice().direct_sum(other.lattice()) base_field = self.base_ring() @@ -1039,7 +1039,7 @@ def __div__(self, other): elif isinstance(other, ModularAbelianVariety_abstract) and other.is_subvariety(self): return self._quotient_by_abelian_subvariety(other) else: - raise TypeError, "other must be a subgroup or abelian subvariety" + raise TypeError("other must be a subgroup or abelian subvariety") def degeneracy_map(self, M_ls, t_ls): """ @@ -1107,16 +1107,16 @@ def degeneracy_map(self, M_ls, t_ls): groups = self.groups() length = len(M_ls) if length != len(t_ls): - raise ValueError, "must have same number of Ms and ts" + raise ValueError("must have same number of Ms and ts") if length != len(groups): - raise ValueError, "must have same number of Ms and groups in ambient variety" + raise ValueError("must have same number of Ms and groups in ambient variety") for i in range(length): N = groups[i].level() if (M_ls[i]%N) and (N%M_ls[i]): - raise ValueError, "one level must divide the other in %s-th component"%i + raise ValueError("one level must divide the other in %s-th component"%i) if (( max(M_ls[i],N) // min(M_ls[i],N) ) % t_ls[i]): - raise ValueError, "each t must divide the quotient of the levels" + raise ValueError("each t must divide the quotient of the levels") ls = [ self.groups()[i].modular_abelian_variety().degeneracy_map(M_ls[i], t_ls[i]).matrix() for i in range(length) ] @@ -1319,7 +1319,7 @@ def projection(self, A, check=True): [0 0] """ if check and not A.is_subvariety(self): - raise ValueError, "A must be an abelian subvariety of self" + raise ValueError("A must be an abelian subvariety of self") W = A.complement(self) mat = A.lattice().basis_matrix().stack(W.lattice().basis_matrix()) @@ -1368,9 +1368,9 @@ def project_to_factor(self, n): [0 1] """ if not self.is_ambient(): - raise ValueError, "self is not ambient" + raise ValueError("self is not ambient") if n >= len(self.groups()): - raise IndexError, "index (=%s) too large (max = %s)"%(n, len(self.groups())) + raise IndexError("index (=%s) too large (max = %s)"%(n, len(self.groups()))) G = self.groups()[n] A = G.modular_abelian_variety() @@ -2229,7 +2229,7 @@ def hecke_polynomial(self, n, var='x'): """ n = Integer(n) if n <= 0: - raise ValueError, "n must be a positive integer" + raise ValueError("n must be a positive integer") key = (n,var) try: return self.__hecke_polynomial[key] @@ -2390,7 +2390,7 @@ def cuspidal_subgroup(self): return self._cuspidal_subgroup except AttributeError: if not self.is_subvariety_of_ambient_jacobian(): - raise ValueError, "self must be a subvariety of the ambient variety" + raise ValueError("self must be a subvariety of the ambient variety") if self.is_ambient(): T = self._ambient_cuspidal_subgroup(rational_only=False) else: @@ -2520,7 +2520,7 @@ def rational_cusp_subgroup(self): return self._rational_cusp_subgroup except AttributeError: if not self.is_subvariety_of_ambient_jacobian(): - raise ValueError, "self must be a subvariety of the ambient variety" + raise ValueError("self must be a subvariety of the ambient variety") if self.is_ambient(): T = self._ambient_cuspidal_subgroup(rational_only=True) else: @@ -2581,7 +2581,7 @@ def rational_cuspidal_subgroup(self): return self._rational_cuspidal_subgroup except AttributeError: if not self.is_subvariety_of_ambient_jacobian(): - raise ValueError, "self must be a subvariety of the ambient variety" + raise ValueError("self must be a subvariety of the ambient variety") if self.is_ambient(): T = self._ambient_cuspidal_subgroup(rational_subgroup=True) else: @@ -2650,14 +2650,14 @@ def finite_subgroup(self, X, field_of_definition=None, check=True): field_of_definition = X.field_of_definition() A = X.abelian_variety() if A.groups() != self.groups(): - raise ValueError, "ambient product Jacobians must be equal" + raise ValueError("ambient product Jacobians must be equal") if A == self: X = X.lattice() else: if X.is_subgroup(self): X = (X.lattice() + self.lattice()).intersection(self.vector_space()) else: - raise ValueError, "X must be a subgroup of self." + raise ValueError("X must be a subgroup of self.") if field_of_definition is None: @@ -2762,7 +2762,7 @@ def degen_t(self, none_if_not_known=False): elif self.dimension() > 0 and self.is_simple(): self.__degen_t = self.decomposition()[0].degen_t() return self.__degen_t - raise ValueError, "self must be simple" + raise ValueError("self must be simple") def isogeny_number(self, none_if_not_known=False): """ @@ -2816,7 +2816,7 @@ def isogeny_number(self, none_if_not_known=False): self.__isogeny_number = self.decomposition()[0].isogeny_number() return self.__isogeny_number else: - raise ValueError, "self must be simple" + raise ValueError("self must be simple") def is_simple(self, none_if_not_known=False): @@ -3253,7 +3253,7 @@ def complement(self, A=None): C = A elif A is not None and self.dimension() == A.dimension(): if not self.is_subvariety(A): - raise ValueError, "self must be a subvariety of A" + raise ValueError("self must be a subvariety of A") C = self.zero_subvariety() else: _, factors, X = self._classify_ambient_factors() @@ -3335,9 +3335,9 @@ def dual(self): return self.__dual except AttributeError: if not self.is_subvariety_of_ambient_jacobian(): - raise NotImplementedError, "dual not implemented unless abelian variety is a subvariety of the ambient Jacobian product" + raise NotImplementedError("dual not implemented unless abelian variety is a subvariety of the ambient Jacobian product") if not self._complement_shares_no_factors_with_same_label(): - raise NotImplementedError, "dual not implemented unless complement shares no simple factors with self." + raise NotImplementedError("dual not implemented unless complement shares no simple factors with self.") C = self.complement() Q, phi = self.ambient_variety().quotient(C) psi = self.ambient_morphism() @@ -3397,7 +3397,7 @@ def _factors_with_same_label(self, other): '11aG1' """ if not isinstance(other, ModularAbelianVariety_abstract): - raise TypeError, "other must be an abelian variety" + raise TypeError("other must be an abelian variety") D = self.decomposition() C = set([A.newform_label() for A in other.decomposition()]) Z = [] @@ -3539,13 +3539,13 @@ def __init__(self, groups, lattice=None, base_field=QQ, is_simple=None, newform_ if check: n = self._ambient_dimension() if not is_FreeModule(lattice): - raise TypeError, "lattice must be a free module" + raise TypeError("lattice must be a free module") if lattice.base_ring() != ZZ: - raise TypeError, "lattice must be over ZZ" + raise TypeError("lattice must be over ZZ") if lattice.degree() != 2*n: - raise ValueError, "lattice must have degree 2*n (=%s)"%(2*n) + raise ValueError("lattice must have degree 2*n (=%s)"%(2*n)) if not lattice.saturation().is_submodule(lattice): # potentially expensive - raise ValueError, "lattice must be full" + raise ValueError("lattice must be full") self.__lattice = lattice @@ -3600,7 +3600,7 @@ def _modular_symbols(self): sage: A._modular_symbols() Modular Symbols subspace of dimension 4 of Modular Symbols space of dimension 5 for Gamma_0(37) of weight 2 with sign 0 over Rational Field """ - raise NotImplementedError, "bug -- must define this" + raise NotImplementedError("bug -- must define this") def __add__(self, other): """ @@ -3632,11 +3632,11 @@ def __add__(self, other): if not is_ModularAbelianVariety(other): if other == 0: return self - raise TypeError, "sum not defined" + raise TypeError("sum not defined") if not isinstance(other, ModularAbelianVariety_modsym_abstract): return ModularAbelianVariety_abstract.__add__(self, other) if self.groups() != other.groups(): - raise TypeError, "sum not defined since ambient spaces different" + raise TypeError("sum not defined since ambient spaces different") M = self.modular_symbols() + other.modular_symbols() return ModularAbelianVariety_modsym(M) @@ -3766,7 +3766,7 @@ def modular_symbols(self, sign=0): """ M = self._modular_symbols().modular_symbols_of_sign(sign) if (sign != 0 and M.dimension() != self.dimension()) or (sign == 0 and M.dimension() != 2*self.dimension()): - raise RuntimeError, "unable to determine sign (=%s) space of modular symbols"%sign + raise RuntimeError("unable to determine sign (=%s) space of modular symbols"%sign) return M def _compute_hecke_polynomial(self, n, var='x'): @@ -4138,11 +4138,11 @@ def __init__(self, modsym, lattice=None, newform_level=None, """ if check: if not isinstance(modsym, ModularSymbolsSpace): - raise TypeError, "modsym must be a modular symbols space" + raise TypeError("modsym must be a modular symbols space") if modsym.sign() != 0: - raise TypeError, "modular symbols space must have sign 0" + raise TypeError("modular symbols space must have sign 0") if not modsym.is_cuspidal(): - raise ValueError, "modsym must be cuspidal" + raise ValueError("modsym must be cuspidal") ModularAbelianVariety_abstract.__init__(self, (modsym.group(), ), modsym.base_ring(), newform_level=newform_level, is_simple=is_simple, @@ -4204,9 +4204,9 @@ def component_group_order(self, p): 11 """ if not self.is_simple(): - raise ValueError, "self must be simple" + raise ValueError("self must be simple") p = Integer(p) - if not p.is_prime(): raise ValueError, "p must be a prime integer" + if not p.is_prime(): raise ValueError("p must be a prime integer") try: return self.__component_group[p][0] except AttributeError: self.__component_group = {} @@ -4218,9 +4218,9 @@ def component_group_order(self, p): return one # Cases that we don't know how to handle yet. if not is_Gamma0(self.group()): - raise NotImplementedError, "computation of component group not implemented when group isn't Gamma0" + raise NotImplementedError("computation of component group not implemented when group isn't Gamma0") if self.level() % (p*p) == 0: - raise NotImplementedError, "computation of component group not implemented when p^2 divides the level" + raise NotImplementedError("computation of component group not implemented when p^2 divides the level") # Now we're on Gamma0(p*M) with gcd(p,M) = 1. # 1. Compute factor of Brandt module space, and put integral structure on it. @@ -4337,16 +4337,16 @@ def tamagawa_number(self, p): except AttributeError: self.__tamagawa_number = {} except KeyError: pass if not self.is_simple(): - raise ValueError, "self must be simple" + raise ValueError("self must be simple") try: g = self.component_group_order(p) except NotImplementedError: - raise NotImplementedError, "Tamagawa number can't be determined using known algorithms, so consider using the tamagawa_number_bounds function instead" + raise NotImplementedError("Tamagawa number can't be determined using known algorithms, so consider using the tamagawa_number_bounds function instead") div, mul, mul_primes = self.tamagawa_number_bounds(p) if div == mul: cp = div else: - raise NotImplementedError, "the Tamagawa number at %s is a power of 2, but the exact power can't be determined using known algorithms. Consider using the tamagawa_number_bounds function instead."%p + raise NotImplementedError("the Tamagawa number at %s is a power of 2, but the exact power can't be determined using known algorithms. Consider using the tamagawa_number_bounds function instead."%p) self.__tamagawa_number[p] = cp return cp @@ -4378,7 +4378,7 @@ def tamagawa_number_bounds(self, p): except AttributeError: self.__tamagawa_number_bounds = {} except KeyError: pass if not self.is_simple(): - raise ValueError, "self must be simple" + raise ValueError("self must be simple") N = self.level() div = 1; mul = 0; mul_primes = [] if N % p != 0: @@ -4403,7 +4403,7 @@ def tamagawa_number_bounds(self, p): div = 2**m mul = 2**n else: - raise NotImplementedError, "Atkin-Lehner at p must act as a scalar" + raise NotImplementedError("Atkin-Lehner at p must act as a scalar") else: mul_primes = list(sorted(set([p] + [q for q in prime_range(2,2*self.dimension()+2)]))) div = Integer(div) @@ -4444,10 +4444,10 @@ def brandt_module(self, p): except KeyError: pass p = Integer(p) if not is_Gamma0(self.group()): - raise NotImplementedError, "Brandt module only defined on Gamma0" - if not p.is_prime(): raise ValueError, "p must be a prime integer" + raise NotImplementedError("Brandt module only defined on Gamma0") + if not p.is_prime(): raise ValueError("p must be a prime integer") if self.level().valuation(p) != 1: - raise ValueError, "p must exactly divide the level" + raise ValueError("p must exactly divide the level") M = self.level() / p from sage.modular.all import BrandtModule V = BrandtModule(p, M) @@ -4461,7 +4461,7 @@ def brandt_module(self, p): V = f(V.hecke_operator(q)).kernel() q = next_prime(q) if V.dimension() > self.dimension(): - raise RuntimeError, "unable to cut out Brandt module (got dimension %s instead of %s)"%(V.dimension(), self.dimension()) + raise RuntimeError("unable to cut out Brandt module (got dimension %s instead of %s)"%(V.dimension(), self.dimension())) else: D = V.decomposition() D = [A for A in D if A.dimension() == self.dimension()] @@ -4472,7 +4472,7 @@ def brandt_module(self, p): D = [A for A in D if A.hecke_polynomial(q) == f] q = next_prime(q) if len(D) != 1: - raise RuntimeError, "unable to locate Brandt module (got %s candidates instead of 1)"%(len(D)) + raise RuntimeError("unable to locate Brandt module (got %s candidates instead of 1)"%(len(D))) V = D[0] self.__brandt_module[p] = V return V @@ -4506,11 +4506,11 @@ def sqrt_poly(f): ValueError: f must be monic """ if not f.is_monic(): - raise ValueError, "f must be monic" + raise ValueError("f must be monic") try: return prod([g**Integer(e/Integer(2)) for g,e in f.factor()]) except TypeError: - raise ValueError, "f must be a perfect square" + raise ValueError("f must be a perfect square") #################################################################################################### @@ -4586,7 +4586,7 @@ def factor_new_space(M): if cube_free: return t.decomposition() t, p = random_hecke_operator(M, t, p) - raise RuntimeError, "unable to factor new space -- this should not happen" # should never happen + raise RuntimeError("unable to factor new space -- this should not happen") # should never happen def factor_modsym_space_new_factors(M): """ diff --git a/src/sage/modular/abvar/abvar_ambient_jacobian.py b/src/sage/modular/abvar/abvar_ambient_jacobian.py index 98fd967254d..4be4a0316c7 100644 --- a/src/sage/modular/abvar/abvar_ambient_jacobian.py +++ b/src/sage/modular/abvar/abvar_ambient_jacobian.py @@ -286,9 +286,9 @@ def degeneracy_map(self, level, t=1, check=True): """ if check: if (level % self.level()) and (self.level() % level): - raise ValueError, "level must be divisible by level of self" + raise ValueError("level must be divisible by level of self") if (max(level,self.level()) // min(self.level(),level)) % t: - raise ValueError, "t must divide the quotient of the two levels" + raise ValueError("t must divide the quotient of the two levels") Mself = self.modular_symbols() #Jdest = Mself.ambient_module().modular_symbols_of_level(level).cuspidal_subspace().abelian_variety() diff --git a/src/sage/modular/abvar/abvar_newform.py b/src/sage/modular/abvar/abvar_newform.py index a48b3b33f31..0c056e5b125 100644 --- a/src/sage/modular/abvar/abvar_newform.py +++ b/src/sage/modular/abvar/abvar_newform.py @@ -45,7 +45,7 @@ def __init__(self, f, internal_name=False): Newform abelian subvariety 37a of dimension 1 of J0(37) """ if not isinstance(f, Newform): - raise TypeError, "f must be a newform" + raise TypeError("f must be a newform") self.__f = f self._is_hecke_stable = True K = f.qexp().base_ring() diff --git a/src/sage/modular/abvar/constructor.py b/src/sage/modular/abvar/constructor.py index 42d882061b2..c5e07047fd8 100644 --- a/src/sage/modular/abvar/constructor.py +++ b/src/sage/modular/abvar/constructor.py @@ -50,7 +50,7 @@ def _get(key): z = _cache[key]() if z is not None: return z - raise ValueError, "element not in cache" + raise ValueError("element not in cache") def _saved(key, J): """ @@ -188,4 +188,4 @@ def AbelianVariety(X): if isinstance(X, (tuple,list)) and all([is_CongruenceSubgroup(G) for G in X]): return abvar.ModularAbelianVariety(X) - raise TypeError, "X must be an integer, string, newform, modsym space, congruence subgroup or tuple of congruence subgroups" + raise TypeError("X must be an integer, string, newform, modsym space, congruence subgroup or tuple of congruence subgroups") diff --git a/src/sage/modular/abvar/cuspidal_subgroup.py b/src/sage/modular/abvar/cuspidal_subgroup.py index ea724ec1e03..d1ca1f30d26 100644 --- a/src/sage/modular/abvar/cuspidal_subgroup.py +++ b/src/sage/modular/abvar/cuspidal_subgroup.py @@ -165,7 +165,7 @@ def _compute_lattice(self, rational_only=False, rational_subgroup=False): if rational_only: # subgroup generated by differences of rational cusps if not is_Gamma0(A.group()): - raise NotImplementedError, 'computation of rational cusps only implemented in Gamma0 case.' + raise NotImplementedError('computation of rational cusps only implemented in Gamma0 case.') if not N.is_squarefree(): data = [n for n in range(2,N) if gcd(n,N) == 1] C = [c for c in C if is_rational_cusp_gamma0(c, N, data)] diff --git a/src/sage/modular/abvar/finite_subgroup.py b/src/sage/modular/abvar/finite_subgroup.py index 22f2067a5ad..193f4598911 100644 --- a/src/sage/modular/abvar/finite_subgroup.py +++ b/src/sage/modular/abvar/finite_subgroup.py @@ -133,9 +133,9 @@ def __init__(self, abvar, field_of_definition=QQ): True """ if field_of_definition not in _Fields: - raise TypeError, "field_of_definition must be a field" + raise TypeError("field_of_definition must be a field") if not abelian_variety.is_ModularAbelianVariety(abvar): - raise TypeError, "abvar must be a modular abelian variety" + raise TypeError("abvar must be a modular abelian variety") Module_old.__init__(self, ZZ) self.__abvar = abvar self.__field_of_definition = field_of_definition @@ -275,7 +275,7 @@ def __add__(self, other): True """ if not isinstance(other, FiniteSubgroup): - raise TypeError, "only addition of two finite subgroups is defined" + raise TypeError("only addition of two finite subgroups is defined") A = self.abelian_variety() B = other.abelian_variety() if not A.in_same_ambient_variety(B): @@ -370,10 +370,10 @@ def intersection(self, other): else: amb = A if not isinstance(other, FiniteSubgroup): - raise TypeError, "only addition of two finite subgroups is defined" + raise TypeError("only addition of two finite subgroups is defined") B = other.abelian_variety() if A.ambient_variety() != B.ambient_variety(): - raise TypeError, "finite subgroups must be in the same ambient product Jacobian" + raise TypeError("finite subgroups must be in the same ambient product Jacobian") M = other.lattice() K = composite_field(self.field_of_definition(), other.field_of_definition()) @@ -645,11 +645,11 @@ def __call__(self, x): elif x.parent().abelian_variety() == self.abelian_variety(): return self(x.element()) else: - raise TypeError, "x does not define an element of self" + raise TypeError("x does not define an element of self") else: z = self.abelian_variety().vector_space()(x) if not z in self.lattice(): - raise TypeError, "x does not define an element of self" + raise TypeError("x does not define an element of self") return TorsionPoint(self, z, check=False) @@ -729,7 +729,7 @@ def subgroup(self, gens): True """ if not isinstance(gens, (tuple, list)): - raise TypeError, "gens must be a list or tuple" + raise TypeError("gens must be a list or tuple") A = self.abelian_variety() lattice = A._ambient_lattice().span([self(g).element() for g in gens]) return FiniteSubgroup_lattice(self.abelian_variety(), lattice, field_of_definition=QQbar) @@ -818,13 +818,13 @@ def __init__(self, abvar, lattice, field_of_definition=QQbar, check=True): """ if check: if not is_FreeModule(lattice) or lattice.base_ring() != ZZ: - raise TypeError, "lattice must be a free module over ZZ" + raise TypeError("lattice must be a free module over ZZ") if not abelian_variety.is_ModularAbelianVariety(abvar): - raise TypeError, "abvar must be a modular abelian variety" + raise TypeError("abvar must be a modular abelian variety") if not abvar.lattice().is_submodule(lattice): lattice += abvar.lattice() if lattice.rank() != abvar.lattice().rank(): - raise ValueError, "lattice must contain the lattice of abvar with finite index" + raise ValueError("lattice must contain the lattice of abvar with finite index") FiniteSubgroup.__init__(self, abvar, field_of_definition) self.__lattice = lattice @@ -879,7 +879,7 @@ def __init__(self, parent, element, check=True): ModuleElement.__init__(self, parent) if check: if not element in parent.abelian_variety().vector_space(): - raise TypeError, "element must be a vector in the abelian variety's rational homology (embedded in the ambient Jacobian product)" + raise TypeError("element must be a vector in the abelian variety's rational homology (embedded in the ambient Jacobian product)") if element.denominator() == 1: element = element.parent().zero_vector() self.__element = element diff --git a/src/sage/modular/abvar/homology.py b/src/sage/modular/abvar/homology.py index 5eaaa831736..3e797d83c1e 100644 --- a/src/sage/modular/abvar/homology.py +++ b/src/sage/modular/abvar/homology.py @@ -110,7 +110,7 @@ def __init__(self, abvar, base): True """ if not is_CommutativeRing(base): - raise TypeError, "base ring must be a commutative ring" + raise TypeError("base ring must be a commutative ring") HeckeModule_free_module.__init__( self, base, abvar.level(), weight=2) self.__abvar = abvar @@ -148,7 +148,7 @@ def _repr_(self): ... NotImplementedError: please override this in the derived class """ - raise NotImplementedError, "please override this in the derived class" + raise NotImplementedError("please override this in the derived class") def gens(self): """ @@ -164,7 +164,7 @@ def gens(self): ... NotImplementedError: homology classes not yet implemented """ - raise NotImplementedError, "homology classes not yet implemented" + raise NotImplementedError("homology classes not yet implemented") def gen(self, n): """ @@ -180,7 +180,7 @@ def gen(self, n): ... NotImplementedError: homology classes not yet implemented """ - raise NotImplementedError, "homology classes not yet implemented" + raise NotImplementedError("homology classes not yet implemented") def abelian_variety(self): """ @@ -583,7 +583,7 @@ def __init__(self, ambient, submodule): True """ if not isinstance(ambient, Homology_abvar): - raise TypeError, "ambient must be the homology of a modular abelian variety" + raise TypeError("ambient must be the homology of a modular abelian variety") self.__ambient = ambient #try: # if not submodule.is_submodule(ambient): diff --git a/src/sage/modular/abvar/homspace.py b/src/sage/modular/abvar/homspace.py index 292d66c7b4c..7823154b2f3 100644 --- a/src/sage/modular/abvar/homspace.py +++ b/src/sage/modular/abvar/homspace.py @@ -221,9 +221,9 @@ def __init__(self, domain, codomain, cat): Category of modular abelian varieties over Rational Field """ if not abelian_variety.is_ModularAbelianVariety(domain): - raise TypeError, "domain must be a modular abelian variety" + raise TypeError("domain must be a modular abelian variety") if not abelian_variety.is_ModularAbelianVariety(codomain): - raise TypeError, "codomain must be a modular abelian variety" + raise TypeError("codomain must be a modular abelian variety") self._gens = None HomsetWithBase.__init__(self, domain, codomain, category=cat) @@ -322,16 +322,16 @@ def __call__(self, M): elif M.domain() == self.domain() and M.codomain() == self.codomain(): M = M.matrix() else: - raise ValueError, "cannot convert %s into %s" % (M, self) + raise ValueError("cannot convert %s into %s" % (M, self)) elif is_Matrix(M): if M.base_ring() != ZZ: M = M.change_ring(ZZ) if M.nrows() != 2*self.domain().dimension() or M.ncols() != 2*self.codomain().dimension(): - raise TypeError, "matrix has wrong dimension" + raise TypeError("matrix has wrong dimension") elif self.matrix_space().has_coerce_map_from(parent(M)): M = self.matrix_space()(M) else: - raise TypeError, "can only coerce in matrices or morphisms" + raise TypeError("can only coerce in matrices or morphisms") return self.element_class(self, M) def _coerce_impl(self, x): @@ -466,7 +466,7 @@ def gen(self, i=0): """ self.calculate_generators() if i > self.ngens(): - raise ValueError, "self only has %s generators"%self.ngens() + raise ValueError("self only has %s generators"%self.ngens()) return self.element_class(self, self._gens[i]) def ngens(self): @@ -844,9 +844,9 @@ def index_in(self, other, check=True): """ if check: if not isinstance(other, EndomorphismSubring): - raise ValueError, "other must be a subring of an endomorphism ring of an abelian variety." + raise ValueError("other must be a subring of an endomorphism ring of an abelian variety.") if not (self.abelian_variety() == other.abelian_variety()): - raise ValueError, "self and other must be endomorphisms of the same abelian variety" + raise ValueError("self and other must be endomorphisms of the same abelian variety") M = self.free_module() N = other.free_module() @@ -948,7 +948,7 @@ def image_of_hecke_algebra(self, check_every=1): A = self.abelian_variety() if not A.is_hecke_stable(): - raise ValueError, "ambient variety is not Hecke stable" + raise ValueError("ambient variety is not Hecke stable") M = A.modular_symbols() diff --git a/src/sage/modular/abvar/lseries.py b/src/sage/modular/abvar/lseries.py index 47d89979209..3e3f88be1f9 100644 --- a/src/sage/modular/abvar/lseries.py +++ b/src/sage/modular/abvar/lseries.py @@ -168,7 +168,7 @@ def __init__(self, abvar, p): Lseries.__init__(self, abvar) p = Integer(p) if not p.is_prime(): - raise ValueError, "p (=%s) must be prime"%p + raise ValueError("p (=%s) must be prime"%p) self.__p = p def __cmp__(self, other): diff --git a/src/sage/modular/abvar/morphism.py b/src/sage/modular/abvar/morphism.py index 024740cffc1..a360fbf7370 100644 --- a/src/sage/modular/abvar/morphism.py +++ b/src/sage/modular/abvar/morphism.py @@ -103,7 +103,7 @@ def complementary_isogeny(self): [0 0 0 2] """ if not self.is_isogeny(): - raise ValueError, "self is not an isogeny" + raise ValueError("self is not an isogeny") M = self.matrix() try: iM, denom = M._invert_iml() @@ -452,7 +452,7 @@ def __call__(self, X): elif isinstance(X, FiniteSubgroup): return self._image_of_finite_subgroup(X) else: - raise TypeError, "X must be an abelian variety or finite subgroup" + raise TypeError("X must be an abelian variety or finite subgroup") def _image_of_element(self, x): """ @@ -597,7 +597,7 @@ def _image_of_abvar(self, A): B = self.matrix() else: if not A.is_subvariety(D): - raise ValueError, "A must be an abelian subvariety of self." + raise ValueError("A must be an abelian subvariety of self.") # Write the vector space corresponding to A in terms of self's # vector space, then take the image under self. B = D.vector_space().coordinate_module(A.vector_space()).basis_matrix() * self.matrix() @@ -645,7 +645,7 @@ def restrict_domain(self, sub): [0 0 0 0] """ if not sub.is_subvariety(self.domain()): - raise ValueError, "sub must be a subvariety of self.domain()" + raise ValueError("sub must be a subvariety of self.domain()") if sub == self.domain(): return self @@ -741,9 +741,9 @@ def __init__(self, abvar, n): """ n = ZZ(n) if n <= 0: - raise ValueError, "n must be positive" + raise ValueError("n must be positive") if not abelian_variety.is_ModularAbelianVariety(abvar): - raise TypeError, "abvar must be a modular abelian variety" + raise TypeError("abvar must be a modular abelian variety") self.__abvar = abvar self.__n = n sage.modules.matrix_morphism.MatrixMorphism_abstract.__init__(self, abvar.Hom(abvar)) diff --git a/src/sage/modular/abvar/torsion_subgroup.py b/src/sage/modular/abvar/torsion_subgroup.py index ad6cc21d50c..d75e83f850e 100644 --- a/src/sage/modular/abvar/torsion_subgroup.py +++ b/src/sage/modular/abvar/torsion_subgroup.py @@ -186,7 +186,7 @@ def order(self): n = O[0] self._order = n return n - raise RuntimeError, "Unable to compute order of torsion subgroup (it is in %s)"%O + raise RuntimeError("Unable to compute order of torsion subgroup (it is in %s)"%O) def lattice(self): """ @@ -236,7 +236,7 @@ def lattice(self): if R.order() == self.multiple_of_order(): return R.lattice() else: - raise NotImplementedError, "unable to compute the rational torsion subgroup in this case (there is no known general algorithm yet)" + raise NotImplementedError("unable to compute the rational torsion subgroup in this case (there is no known general algorithm yet)") def possible_orders(self): """ @@ -362,7 +362,7 @@ def multiple_of_order(self, maxp=None): # then compute some charpoly involving # that directly... # (2) use (1) -- see my MAGMA code. - raise NotImplementedError, "torsion multiple only implemented for Gamma0" + raise NotImplementedError("torsion multiple only implemented for Gamma0") cnt = 0 if maxp is None: X = Primes() diff --git a/src/sage/modular/arithgroup/arithgroup_generic.py b/src/sage/modular/arithgroup/arithgroup_generic.py index 287eb88bc4f..215c2386413 100644 --- a/src/sage/modular/arithgroup/arithgroup_generic.py +++ b/src/sage/modular/arithgroup/arithgroup_generic.py @@ -108,7 +108,7 @@ def __reduce__(self): ... NotImplementedError: all subclasses must define a __reduce__ method """ - raise NotImplementedError, "all subclasses must define a __reduce__ method" + raise NotImplementedError("all subclasses must define a __reduce__ method") def _element_constructor_(self, x, check=True): r""" @@ -137,7 +137,7 @@ def _element_constructor_(self, x, check=True): x = SL2Z(x, check) if not check or x in self: return x - raise TypeError, "matrix %s is not an element of %s" % (x, self) + raise TypeError("matrix %s is not an element of %s" % (x, self)) def __contains__(self, x): r""" @@ -188,7 +188,7 @@ def _contains_sl2(self, a,b,c,d): ... NotImplementedError: Please implement _contains_sl2 for """ - raise NotImplementedError, "Please implement _contains_sl2 for %s" % self.__class__ + raise NotImplementedError("Please implement _contains_sl2 for %s" % self.__class__) def __hash__(self): r""" @@ -323,7 +323,7 @@ def todd_coxeter(self, G=None, on_right=True): if G is None: G = SL2Z if G != SL2Z: - raise NotImplementedError, "Don't know how to compute coset reps for subgroups yet" + raise NotImplementedError("Don't know how to compute coset reps for subgroups yet") id = SL2Z([1,0,0,1]) l = SL2Z([1,1,0,1]) @@ -712,7 +712,7 @@ def cusps(self, algorithm='default'): elif algorithm == 'modsym': s = sorted([self.reduce_cusp(c) for c in self.modular_symbols().cusps()]) else: - raise ValueError, "unknown algorithm: %s"%algorithm + raise ValueError("unknown algorithm: %s"%algorithm) self._cusp_list[algorithm] = s return copy(s) @@ -823,7 +823,7 @@ def cusp_data(self, c): return (g * SL2Z([1,d,0,1]) * (~g), d, 1) elif g * SL2Z([-1,-d,0,-1]) * (~g) in self: return (g * SL2Z([-1,-d,0,-1]) * (~g), d, -1) - raise ArithmeticError, "Can't get here!" + raise ArithmeticError("Can't get here!") def is_regular_cusp(self, c): r""" @@ -1014,7 +1014,7 @@ def generators(self, algorithm="farey"): elif algorithm == "todd-coxeter": return self.todd_coxeter()[1] else: - raise ValueError, "Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm + raise ValueError("Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm) def gens(self, *args, **kwds): r""" @@ -1162,7 +1162,7 @@ def dimension_modular_forms(self, k=2): if e_reg > 2*self.genus() - 2: return e_reg / ZZ(2) else: - raise NotImplementedError, "Computation of dimensions of weight 1 modular forms spaces not implemented in general" + raise NotImplementedError("Computation of dimensions of weight 1 modular forms spaces not implemented in general") def dimension_cusp_forms(self, k=2): r""" @@ -1222,7 +1222,7 @@ def dimension_cusp_forms(self, k=2): if e_reg > 2*self.genus() - 2: return ZZ(0) else: - raise NotImplementedError, "Computation of dimensions of weight 1 cusp forms spaces not implemented in general" + raise NotImplementedError("Computation of dimensions of weight 1 cusp forms spaces not implemented in general") def dimension_eis(self, k=2): r""" diff --git a/src/sage/modular/arithgroup/arithgroup_perm.py b/src/sage/modular/arithgroup/arithgroup_perm.py index 66e2c4b5372..0bfa82305e0 100644 --- a/src/sage/modular/arithgroup/arithgroup_perm.py +++ b/src/sage/modular/arithgroup/arithgroup_perm.py @@ -392,7 +392,7 @@ def ArithmeticSubgroup_Permutation( if len(gens) == 0: S2 = S3 = L = R = '' elif len(gens) < 2: - raise ValueError, "Need at least two generators" + raise ValueError("Need at least two generators") if S2 is not None: S2 = PermutationGroupElement(S2,check=check) @@ -437,15 +437,15 @@ def ArithmeticSubgroup_Permutation( R = S3 * S2 if check and (L != ~S3 * ~S2 or R != S3 * S2): - raise ValueError, "Wrong relations between generators" + raise ValueError("Wrong relations between generators") inv = S2*S2 if check: if inv != S3*S3*S3: - raise ValueError, "S2^2 does not equal to S3^3" + raise ValueError("S2^2 does not equal to S3^3") elif not (inv*inv).is_one(): - raise ValueError, "S2^2 = S3^3 must have order 1 or 2" + raise ValueError("S2^2 = S3^3 must have order 1 or 2") # Check transitivity. This is the most expensive check, so we do it # last. @@ -453,7 +453,7 @@ def ArithmeticSubgroup_Permutation( G = PermutationGroup(gens) if not G.is_transitive(): - raise ValueError, "Permutations do not generate a transitive group" + raise ValueError("Permutations do not generate a transitive group") s2 = [i-1 for i in S2.domain()] s3 = [i-1 for i in S3.domain()] @@ -2087,7 +2087,7 @@ def todd_coxeter_s2_s3(self): elif e[2] == 's3': gens.append(self(reps[e[0]] * S3m * ~reps[e[1]])) else: - raise ValueError, "this should not happen" + raise ValueError("this should not happen") return reps, gens, self._S2[:], self._S3[:] @@ -2134,7 +2134,7 @@ def todd_coxeter_l_s2(self): elif e[2] == 's': gens.append(self(reps[e[0]] * S2m * ~reps[e[1]])) else: - raise ValueError, "this should not happen" + raise ValueError("this should not happen") return reps, gens, self._L[:], self._S2[:] @@ -2401,7 +2401,7 @@ def one_odd_subgroup(self,random=False): True """ if self.nu2() != 0: - raise ValueError, "Group contains an element of order 4, hence no index 2 odd subgroups" + raise ValueError("Group contains an element of order 4, hence no index 2 odd subgroups") n = self.index() s2old, s3old = self.S2(), self.S3() s2cycs = s2old.cycle_tuples() # no singletons can exist diff --git a/src/sage/modular/arithgroup/congroup_gamma.py b/src/sage/modular/arithgroup/congroup_gamma.py index 392f63fc7a4..dd7b4b263a9 100644 --- a/src/sage/modular/arithgroup/congroup_gamma.py +++ b/src/sage/modular/arithgroup/congroup_gamma.py @@ -343,5 +343,5 @@ def _lift_pair(U,V,N): v = N while gcd(u, v) > 1: u = u+N - if u > N*v: raise ValueError, "(U, V, N) must be coprime" + if u > N*v: raise ValueError("(U, V, N) must be coprime") return (u, v) diff --git a/src/sage/modular/arithgroup/congroup_gamma0.py b/src/sage/modular/arithgroup/congroup_gamma0.py index ec663605c91..f00ce991b9e 100644 --- a/src/sage/modular/arithgroup/congroup_gamma0.py +++ b/src/sage/modular/arithgroup/congroup_gamma0.py @@ -384,7 +384,7 @@ def generators(self, algorithm="farey"): return [self(g, check=False) for g in gen_list] else: - raise ValueError, "Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm + raise ValueError("Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm) def gamma_h_subgroups(self): r""" diff --git a/src/sage/modular/arithgroup/congroup_gamma1.py b/src/sage/modular/arithgroup/congroup_gamma1.py index 2053acf139a..cc216728bbe 100644 --- a/src/sage/modular/arithgroup/congroup_gamma1.py +++ b/src/sage/modular/arithgroup/congroup_gamma1.py @@ -233,7 +233,7 @@ def generators(self, algorithm="farey"): gen_list = generators_helper(G1list(level), level, Mat2Z) return [self(g, check=False) for g in gen_list] else: - raise ValueError, "Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm + raise ValueError("Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm) def _contains_sl2(self, a,b,c,d): r""" @@ -443,7 +443,7 @@ def dimension_cusp_forms(self, k=2, eps=None, algorithm="CohenOesterle"): if n == 0: return ZZ(0) else: # never happens at present - raise NotImplementedError, "Computations of dimensions of spaces of weight 1 cusp forms not implemented at present" + raise NotImplementedError("Computations of dimensions of spaces of weight 1 cusp forms not implemented at present") except NotImplementedError: raise @@ -464,7 +464,7 @@ def dimension_cusp_forms(self, k=2, eps=None, algorithm="CohenOesterle"): return ZZ( K(Gamma0(N).index() * (k-1)/ZZ(12)) + CohenOesterle(eps,k) ) else: #algorithm not in ["CohenOesterle", "Quer"]: - raise ValueError, "Unrecognised algorithm in dimension_cusp_forms" + raise ValueError("Unrecognised algorithm in dimension_cusp_forms") def dimension_eis(self, k=2, eps=None, algorithm="CohenOesterle"): @@ -551,7 +551,7 @@ def dimension_eis(self, k=2, eps=None, algorithm="CohenOesterle"): return alpha - self.dimension_cusp_forms(k, eps) else: #algorithm not in ["CohenOesterle", "Quer"]: - raise ValueError, "Unrecognised algorithm in dimension_eis" + raise ValueError("Unrecognised algorithm in dimension_eis") def dimension_new_cusp_forms(self, k=2, eps=None, p=0, algorithm="CohenOesterle"): r""" diff --git a/src/sage/modular/arithgroup/congroup_gammaH.py b/src/sage/modular/arithgroup/congroup_gammaH.py index d051ccf5b15..3d4f13044b4 100644 --- a/src/sage/modular/arithgroup/congroup_gammaH.py +++ b/src/sage/modular/arithgroup/congroup_gammaH.py @@ -136,7 +136,7 @@ def _normalize_H(H, level): H = [ZZ(h) for h in H] for h in H: if gcd(h, level) > 1: - raise ArithmeticError, 'The generators %s must be units modulo %s'%(H, level) + raise ArithmeticError('The generators %s must be units modulo %s'%(H, level)) H = list(set([h%level for h in H])) H.sort() if 1 in H: @@ -225,7 +225,7 @@ def restrict(self, M): """ M = ZZ(M) if self.level() % M: - raise ValueError, "M (=%s) must be a divisor of the level (%s) of self" % (M, self.level()) + raise ValueError("M (=%s) must be a divisor of the level (%s) of self" % (M, self.level())) return self._new_group_from_level(M) def extend(self, M): @@ -247,7 +247,7 @@ def extend(self, M): """ M = ZZ(M) if M % self.level(): - raise ValueError, "M (=%s) must be a multiple of the level (%s) of self" % (M, self.level()) + raise ValueError("M (=%s) must be a multiple of the level (%s) of self" % (M, self.level())) return self._new_group_from_level(M) def __reduce__(self): @@ -479,7 +479,7 @@ def generators(self, algorithm="farey"): gen_list = generators_helper(GHlist(self), level, Mat2Z) return [self(g, check=False) for g in gen_list] else: - raise ValueError, "Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm + raise ValueError("Unknown algorithm '%s' (should be either 'farey' or 'todd-coxeter')" % algorithm) def _coset_reduction_data_first_coord(G): """ @@ -1203,7 +1203,7 @@ def image_mod_n(self): """ N = self.level() if N == 1: - raise NotImplementedError, "Matrix groups over ring of integers modulo 1 not implemented" + raise NotImplementedError("Matrix groups over ring of integers modulo 1 not implemented") gens = [matrix(Zmod(N), 2, 2, [x, 0, 0, Zmod(N)(1)/x]) for x in self._generators_for_H()] gens += [matrix(Zmod(N),2,[1,1,0,1])] return MatrixGroup(gens) @@ -1223,7 +1223,7 @@ def _list_subgroup(N, gens): N = int(N) for g in gens: if gcd(g, N) != 1: - raise ValueError, "gen (=%s) is not in (Z/%sZ)^*"%(g,N) + raise ValueError("gen (=%s) is not in (Z/%sZ)^*"%(g,N)) gk = int(g) % N sbgrp = [gk] while not (gk in H): @@ -1286,7 +1286,7 @@ def mumu(N): 1 """ if N < 1: - raise ValueError, "N must be at least 1" + raise ValueError("N must be at least 1") p = 1 for _,r in factor(N): if r > 2: diff --git a/src/sage/modular/arithgroup/congroup_generic.py b/src/sage/modular/arithgroup/congroup_generic.py index 0ebe97dac9d..d02ecb3b5a3 100644 --- a/src/sage/modular/arithgroup/congroup_generic.py +++ b/src/sage/modular/arithgroup/congroup_generic.py @@ -99,10 +99,10 @@ def CongruenceSubgroup_constructor(*args): R = G.matrix_space().base_ring() if not hasattr(R, "cover_ring") or R.cover_ring() != ZZ: - raise TypeError, "Ring of definition must be Z / NZ for some N" + raise TypeError("Ring of definition must be Z / NZ for some N") if not all([x.matrix().det() == 1 for x in G.gens()]): - raise ValueError, "Group must be contained in SL(2, Z / N)" + raise ValueError("Group must be contained in SL(2, Z / N)") GG = _minimize_level(G) if GG in ZZ: from all import Gamma @@ -152,7 +152,7 @@ def __init__(self, level): """ level = ZZ(level) if level <= 0: - raise ArithmeticError, "Congruence groups only defined for positive levels." + raise ArithmeticError("Congruence groups only defined for positive levels.") self.__level = level ArithmeticSubgroup.__init__(self) @@ -503,7 +503,7 @@ def _new_group_from_level(self, level): from all import Gamma0, Gamma1, GammaH N = self.level() if (level%N) and (N%level): - raise ValueError, "one level must divide the other" + raise ValueError("one level must divide the other") if is_Gamma0(self): return Gamma0(level) elif is_Gamma1(self): diff --git a/src/sage/modular/arithgroup/tests.py b/src/sage/modular/arithgroup/tests.py index 38baca999eb..b9035181690 100644 --- a/src/sage/modular/arithgroup/tests.py +++ b/src/sage/modular/arithgroup/tests.py @@ -270,7 +270,7 @@ def test_relabel(self): print "ss2 = %s" %str(ss2) print "ss3 = %s" %str(ss3) print "pp = %s" %str(pp) - raise AssertionError, "%s does not coincide" %elt + raise AssertionError("%s does not coincide" %elt) def test_congruence_groups(self): r""" @@ -287,7 +287,7 @@ def test_congruence_groups(self): GG = G.as_permutation_group() if not GG.is_congruence(): - raise AssertionError, "Hsu congruence test failed" + raise AssertionError("Hsu congruence test failed") methods = [ 'index', @@ -303,15 +303,15 @@ def test_congruence_groups(self): for f in methods: if getattr(G,f)() != getattr(GG,f)(): - raise AssertionError, "results of %s does not coincide for %s" %(f,G) + raise AssertionError("results of %s does not coincide for %s" %(f,G)) if sorted((G.cusp_width(c) for c in G.cusps())) != GG.cusp_widths(): - raise AssertionError, "Cusps widths are different for %s" %G + raise AssertionError("Cusps widths are different for %s" %G) for _ in xrange(20): m = GG.random_element() if m not in G: - raise AssertionError, "random element generated by perm. group not in %s" %(str(m),str(G)) + raise AssertionError("random element generated by perm. group not in %s" %(str(m),str(G))) def test_contains(self): r""" @@ -331,7 +331,7 @@ def test_contains(self): for _ in xrange(20): g = G.random_element() if G.random_element() not in G: - raise AssertionError, "%s not in %s" %(g,G) + raise AssertionError("%s not in %s" %(g,G)) def test_spanning_trees(self): r""" diff --git a/src/sage/modular/cusps.py b/src/sage/modular/cusps.py index b9ff0674d17..2916976166c 100644 --- a/src/sage/modular/cusps.py +++ b/src/sage/modular/cusps.py @@ -304,7 +304,7 @@ def __init__(self, a, b=None, parent=None, check=True): self.__b = ZZ(1) elif isinstance(a, (tuple, list)): if len(a) != 2: - raise TypeError, "Unable to convert %s to a Cusp"%a + raise TypeError("Unable to convert %s to a Cusp"%a) if ZZ(a[1]) == 0: self.__a = ZZ(1) self.__b = ZZ(0) @@ -314,25 +314,25 @@ def __init__(self, a, b=None, parent=None, check=True): self.__a = r.numer() self.__b = r.denom() except (ValueError, TypeError): - raise TypeError, "Unable to convert %s to a Cusp"%a + raise TypeError("Unable to convert %s to a Cusp"%a) else: try: r = QQ(a) self.__a = r.numer() self.__b = r.denom() except (ValueError, TypeError): - raise TypeError, "Unable to convert %s to a Cusp"%a + raise TypeError("Unable to convert %s to a Cusp"%a) return if is_InfinityElement(b): if is_InfinityElement(a) or (isinstance(a, Cusp) and a.is_infinity()): - raise TypeError, "Unable to convert (%s, %s) to a Cusp"%(a, b) + raise TypeError("Unable to convert (%s, %s) to a Cusp"%(a, b)) self.__a = ZZ(0) self.__b = ZZ(1) return elif not b: if not a: - raise TypeError, "Unable to convert (%s, %s) to a Cusp"%(a, b) + raise TypeError("Unable to convert (%s, %s) to a Cusp"%(a, b)) self.__a = ZZ(1) self.__b = ZZ(0) return @@ -354,13 +354,13 @@ def __init__(self, a, b=None, parent=None, check=True): r = ZZ(a) / b elif isinstance(a, (tuple, list)): if len(a) != 2: - raise TypeError, "Unable to convert (%s, %s) to a Cusp"%(a, b) + raise TypeError("Unable to convert (%s, %s) to a Cusp"%(a, b)) r = ZZ(a[0]) / (ZZ(a[1]) * b) else: try: r = QQ(a) / b except (ValueError, TypeError): - raise TypeError, "Unable to convert (%s, %s) to a Cusp"%(a, b) + raise TypeError("Unable to convert (%s, %s) to a Cusp"%(a, b)) self.__a = r.numer() self.__b = r.denom() @@ -530,7 +530,7 @@ def _rational_(self): pass if not self.__b: - raise TypeError, "cusp %s is not a rational number"%self + raise TypeError("cusp %s is not a rational number"%self) self.__rational = self.__a / self.__b return self.__rational @@ -557,7 +557,7 @@ def _integer_(self, ZZ=None): TypeError: cusp -3/7 is not an integer """ if self.__b != 1: - raise TypeError, "cusp %s is not an integer"%self + raise TypeError("cusp %s is not an integer"%self) return self.__a def _repr_(self): @@ -668,7 +668,7 @@ def is_gamma0_equiv(self, other, N, transformation = None): Modular Elliptic Curves', or Prop 2.27 of Stein's Ph.D. thesis. """ if transformation not in [False,True,"matrix",None,"corner"]: - raise ValueError, "Value %s of the optional argument transformation is not valid." + raise ValueError("Value %s of the optional argument transformation is not valid.") if not isinstance(other, Cusp): other = Cusp(other) @@ -928,7 +928,7 @@ def is_gamma_h_equiv(self, other, G): if not isinstance(other, Cusp): other = Cusp(other) if not is_GammaH(G): - raise TypeError, "G must be a group GammaH(N)." + raise TypeError("G must be a group GammaH(N).") H = G._list_of_elements_in_H() N = ZZ(G.level()) diff --git a/src/sage/modular/cusps_nf.py b/src/sage/modular/cusps_nf.py index 34abe24d098..214172a37c2 100644 --- a/src/sage/modular/cusps_nf.py +++ b/src/sage/modular/cusps_nf.py @@ -521,7 +521,7 @@ def __init__(self, number_field, a, b=None, parent=None, lreps=None): self.__a = R(a.__a) self.__b = R(a.__b) else: - raise ValueError, "Cannot coerce cusps from one field to another" + raise ValueError("Cannot coerce cusps from one field to another") elif a in R: self.__a = R(a) self.__b = R(1) @@ -536,8 +536,8 @@ def __init__(self, number_field, a, b=None, parent=None, lreps=None): self.__b = R(1) elif isinstance(a, (tuple, list)): if len(a) != 2: - raise TypeError, "Unable to convert %s to a cusp \ - of the number field"%a + raise TypeError("Unable to convert %s to a cusp \ + of the number field"%a) if a[1].is_zero(): self.__a = R(1) self.__b = R(0) @@ -558,28 +558,28 @@ def __init__(self, number_field, a, b=None, parent=None, lreps=None): self.__b = R(r.denominator()) self.__a = R(r * self.__b) except (ValueError, TypeError): - raise TypeError, "Unable to convert %s to a cusp \ - of the number field"%a + raise TypeError("Unable to convert %s to a cusp \ + of the number field"%a) else: try: r = number_field(a) self.__b = R(r.denominator()) self.__a = R(r * self.__b) except (ValueError, TypeError): - raise TypeError, "Unable to convert %s to a cusp \ - of the number field"%a + raise TypeError("Unable to convert %s to a cusp \ + of the number field"%a) else:#'b' is given if is_InfinityElement(b): if is_InfinityElement(a) or (isinstance(a, NFCusp) and a.is_infinity()): - raise TypeError, "Unable to convert (%s, %s) \ - to a cusp of the number field"%(a, b) + raise TypeError("Unable to convert (%s, %s) \ + to a cusp of the number field"%(a, b)) self.__a = R(0) self.__b = R(1) return elif not b: if not a: - raise TypeError, "Unable to convert (%s, %s) \ - to a cusp of the number field"%(a, b) + raise TypeError("Unable to convert (%s, %s) \ + to a cusp of the number field"%(a, b)) self.__a = R(1) self.__b = R(0) return @@ -607,15 +607,15 @@ def __init__(self, number_field, a, b=None, parent=None, lreps=None): r = R(a) / b elif isinstance(a, (tuple, list)): if len(a) != 2: - raise TypeError, "Unable to convert (%s, %s) \ - to a cusp of the number field"%(a, b) + raise TypeError("Unable to convert (%s, %s) \ + to a cusp of the number field"%(a, b)) r = R(a[0]) / (R(a[1]) * b) else: try: r = number_field(a) / b except (ValueError, TypeError): - raise TypeError, "Unable to convert (%s, %s) \ - to a cusp of the number field"%(a, b) + raise TypeError("Unable to convert (%s, %s) \ + to a cusp of the number field"%(a, b)) self.__b = R(r.denominator()) self.__a = R(r * self.__b) if not lreps is None: @@ -732,8 +732,8 @@ def _number_field_element_(self): -1/3*a + 1/3 """ if self.__b.is_zero(): - raise TypeError, "%s is not an element of %s"%(self, \ - self.number_field()) + raise TypeError("%s is not an element of %s"%(self, \ + self.number_field())) k = self.number_field() return k(self.__a / self.__b) @@ -755,13 +755,13 @@ def _ring_of_integers_element_(self): if self.__b.is_one(): return self.__a if self.__b.is_zero(): - raise TypeError, "%s is not an element of %s"%(self, \ - self.number_field.ring_of_integers()) + raise TypeError("%s is not an element of %s"%(self, \ + self.number_field.ring_of_integers())) R = self.number_field().ring_of_integers() try: return R(self.__a/self.__b) except (ValueError, TypeError): - raise TypeError, "%s is not an integral element"%self + raise TypeError("%s is not an integral element"%self) def _latex_(self): r""" diff --git a/src/sage/modular/dims.py b/src/sage/modular/dims.py index 76683d37e55..8b654a57c46 100644 --- a/src/sage/modular/dims.py +++ b/src/sage/modular/dims.py @@ -75,7 +75,7 @@ def eisen(p): [(2, 1), (3, 1), (5, 1), (7, 1), (11, 5), (13, 1), (17, 4), (19, 3), (23, 11)] """ if not is_prime(p): - raise ValueError, "p must be prime" + raise ValueError("p must be prime") return frac(p-1,12).numerator() ########################################################################## @@ -111,7 +111,7 @@ def CO_delta(r,p,N,eps): 2 """ if not is_prime(p): - raise ValueError, "p must be prime" + raise ValueError("p must be prime") K = eps.base_ring() if p%4 == 3: return K(0) @@ -319,7 +319,7 @@ def dimension_new_cusp_forms(X, k=2, p=0): elif isinstance(X, (int,long,Integer)): return Gamma0(X).dimension_new_cusp_forms(k,p=p) else: - raise TypeError, "X (=%s) must be an integer, a Dirichlet character or a congruence subgroup of type Gamma0, Gamma1 or GammaH" % X + raise TypeError("X (=%s) must be an integer, a Dirichlet character or a congruence subgroup of type Gamma0, Gamma1 or GammaH" % X) def dimension_cusp_forms(X, k=2): r""" @@ -431,7 +431,7 @@ def dimension_cusp_forms(X, k=2): elif isinstance(X, (Integer,int,long)): return Gamma0(X).dimension_cusp_forms(k) else: - raise TypeError, "Argument 1 must be a Dirichlet character, an integer or a finite index subgroup of SL2Z" + raise TypeError("Argument 1 must be a Dirichlet character, an integer or a finite index subgroup of SL2Z") def dimension_eis(X, k=2): """ @@ -515,7 +515,7 @@ def dimension_eis(X, k=2): elif isinstance(X, (int, long, Integer)): return Gamma0(X).dimension_eis(k) else: - raise TypeError, "Argument in dimension_eis must be an integer, a Dirichlet character, or a finite index subgroup of SL2Z (got %s)" % X + raise TypeError("Argument in dimension_eis must be an integer, a Dirichlet character, or a finite index subgroup of SL2Z (got %s)" % X) def dimension_modular_forms(X, k=2): r""" @@ -562,7 +562,7 @@ def dimension_modular_forms(X, k=2): elif isinstance(X,dirichlet.DirichletCharacter): return Gamma1(X.modulus()).dimension_modular_forms(k, eps=X) else: - raise TypeError, "Argument 1 must be an integer, a Dirichlet character or an arithmetic subgroup." + raise TypeError("Argument 1 must be an integer, a Dirichlet character or an arithmetic subgroup.") def sturm_bound(level, weight=2): r""" @@ -596,6 +596,6 @@ def sturm_bound(level, weight=2): if level.is_congruence(): return level.sturm_bound(weight) else: - raise ValueError, "No Sturm bound defined for noncongruence subgroups" + raise ValueError("No Sturm bound defined for noncongruence subgroups") if isinstance(level, (int, long, Integer)): return Gamma0(level).sturm_bound(weight) diff --git a/src/sage/modular/dirichlet.py b/src/sage/modular/dirichlet.py index 3d480352f6b..89ec9537fb9 100644 --- a/src/sage/modular/dirichlet.py +++ b/src/sage/modular/dirichlet.py @@ -121,7 +121,7 @@ def kronecker_character(d): """ d = rings.Integer(d) if d == 0: - raise ValueError, "d must be nonzero" + raise ValueError("d must be nonzero") D = arith.fundamental_discriminant(d) G = DirichletGroup(abs(D), rings.RationalField()) @@ -144,7 +144,7 @@ def kronecker_character_upside_down(d): """ d = rings.Integer(d) if d <= 0: - raise ValueError, "d must be positive" + raise ValueError("d must be positive") G = DirichletGroup(d, rings.RationalField()) return G([arith.kronecker(u.lift(),d) for u in G.unit_gens()]) @@ -218,9 +218,8 @@ def __init__(self, parent, x, check=True): self.__modulus = parent.modulus() if check: if len(x) != len(parent.unit_gens()): - raise ValueError, \ - "wrong number of values(=%s) on unit gens (want %s)"%( \ - x,len(parent.unit_gens())) + raise ValueError("wrong number of values(=%s) on unit gens (want %s)"%( \ + x,len(parent.unit_gens()))) if free_module_element.is_FreeModuleElement(x): self.__element = parent._module(x) else: @@ -636,7 +635,7 @@ def bernoulli(self, k, algorithm='recurrence', cache=True, **opts): ber = sum([self(a)*h[a][k] for a in range(1,N+1)]) * arith.factorial(k) else: - raise ValueError, "algorithm = '%s' unknown"%algorithm + raise ValueError("algorithm = '%s' unknown"%algorithm) if cache: self.__bernoulli[k] = ber @@ -750,7 +749,7 @@ def extend(self, M): True """ if M % self.modulus() != 0: - raise ArithmeticError, "M(=%s) must be a multiple of the modulus(=%s)"%(M,self.modulus()) + raise ArithmeticError("M(=%s) must be a multiple of the modulus(=%s)"%(M,self.modulus())) H = DirichletGroup(M, self.base_ring()) return H(self) @@ -791,7 +790,7 @@ def galois_orbit(self, sort=True): TypeError: Galois orbits only defined if base ring is an integral domain """ if not self.base_ring().is_integral_domain(): - raise TypeError, "Galois orbits only defined if base ring is an integral domain" + raise TypeError("Galois orbits only defined if base ring is an integral domain") k = self.order() if k <= 2: return [self] @@ -849,7 +848,7 @@ def gauss_sum(self, a=1): G = self.parent() K = G.base_ring() if not (rings.is_CyclotomicField(K) or is_RationalField(K)): - raise NotImplementedError, "Gauss sums only currently implemented when the base ring is a cyclotomic field or QQ." + raise NotImplementedError("Gauss sums only currently implemented when the base ring is a cyclotomic field or QQ.") g = 0 m = G.modulus() L = rings.CyclotomicField(arith.lcm(m,G.zeta_order())) @@ -912,7 +911,7 @@ def gauss_sum_numerical(self, prec=53, a=1): G = self.parent() K = G.base_ring() if not (rings.is_CyclotomicField(K) or is_RationalField(K)): - raise NotImplementedError, "Gauss sums only currently implemented when the base ring is a cyclotomic field or QQ." + raise NotImplementedError("Gauss sums only currently implemented when the base ring is a cyclotomic field or QQ.") phi = K.complex_embedding(prec) CC = phi.codomain() @@ -1029,7 +1028,7 @@ def jacobi_sum(self, char, check=True): """ if check: if self.parent() != char.parent(): - raise NotImplementedError, "Characters must be from the same Dirichlet Group." + raise NotImplementedError("Characters must be from the same Dirichlet Group.") return sum([self(x) * char(1-x) for x in rings.IntegerModRing(self.modulus())]) @@ -1069,7 +1068,7 @@ def kloosterman_sum(self, a=1,b=0): G = self.parent() K = G.base_ring() if not (rings.is_CyclotomicField(K) or is_RationalField(K)): - raise NotImplementedError, "Kloosterman sums only currently implemented when the base ring is a cyclotomic field or QQ." + raise NotImplementedError("Kloosterman sums only currently implemented when the base ring is a cyclotomic field or QQ.") g = 0 m = G.modulus() L = rings.CyclotomicField(arith.lcm(m,G.zeta_order())) @@ -1116,7 +1115,7 @@ def kloosterman_sum_numerical(self, prec=53, a=1,b=0): G = self.parent() K = G.base_ring() if not (rings.is_CyclotomicField(K) or is_RationalField(K)): - raise NotImplementedError, "Kloosterman sums only currently implemented when the base ring is a cyclotomic field or QQ." + raise NotImplementedError("Kloosterman sums only currently implemented when the base ring is a cyclotomic field or QQ.") phi = K.complex_embedding(prec) CC = phi.codomain() g = 0 @@ -1405,9 +1404,9 @@ def restrict(self, M): """ M = int(M) if self.modulus()%M != 0: - raise ValueError, "M(=%s) must divide the modulus(=%s)"%(M,self.modulus()) + raise ValueError("M(=%s) must divide the modulus(=%s)"%(M,self.modulus())) if M%self.conductor() != 0: - raise ValueError, "conductor(=%s) must divide M(=%s)"%(self.conductor(),M) + raise ValueError("conductor(=%s) must divide M(=%s)"%(self.conductor(),M)) H = DirichletGroup(M, self.base_ring()) return H(self) @@ -1738,14 +1737,14 @@ def DirichletGroup(modulus, base_ring=None, zeta=None, zeta_order=None, if base_ring is None: if not (zeta is None and zeta_order is None): - raise ValueError, "zeta and zeta_order must be None if base_ring not specified." + raise ValueError("zeta and zeta_order must be None if base_ring not specified.") e = rings.IntegerModRing(modulus).unit_group_exponent() base_ring = rings.CyclotomicField(e) if integral: base_ring = base_ring.ring_of_integers() if not is_Ring(base_ring): - raise TypeError, "base_ring (=%s) must be a ring"%base_ring + raise TypeError("base_ring (=%s) must be a ring"%base_ring) if zeta is None: e = rings.IntegerModRing(modulus).unit_group_exponent() @@ -1852,7 +1851,7 @@ def base_extend(self, R): """ if not R.has_coerce_map_from(self.base_ring()): - raise TypeError, "No coercion map from '%s' to '%s' is defined." % (self.base_ring(), R) + raise TypeError("No coercion map from '%s' to '%s' is defined." % (self.base_ring(), R)) return DirichletGroup(self.modulus(), R, zeta=R(self.zeta()), zeta_order=self.zeta_order()) def __call__(self, x): @@ -1885,7 +1884,7 @@ def __call__(self, x): elif x.parent() == self: return DirichletCharacter(self, x.values_on_gens()) return self._coerce_in_dirichlet_character(x) - raise TypeError, "No coercion of %s into %s defined."%(x, self) + raise TypeError("No coercion of %s into %s defined."%(x, self)) def _coerce_in_dirichlet_character(self, x): r""" @@ -1910,9 +1909,9 @@ def _coerce_in_dirichlet_character(self, x): """ if self.modulus() % x.conductor() != 0: - raise TypeError, "conductor must divide modulus" + raise TypeError("conductor must divide modulus") elif not x.order().divides(self._zeta_order): - raise ValueError, "cannot coerce element of order %s into self"%x.order() + raise ValueError("cannot coerce element of order %s into self"%x.order()) a = [] R = self.base_ring() for u in self.unit_gens(): @@ -2109,7 +2108,7 @@ def _automorphisms(self): Auts = [e for e in xrange(1,n) if arith.GCD(e,n) == 1] else: if not rings.ZZ(p).is_prime(): - raise NotImplementedError, "Automorphisms for finite non-field base rings not implemented" + raise NotImplementedError("Automorphisms for finite non-field base rings not implemented") # The automorphisms in characteristic p are # k-th powering for # k = 1, p, p^2, ..., p^(r-1), @@ -2212,7 +2211,7 @@ def gen(self, n=0): n = int(n) g = self.gens() if n<0 or n>=len(g): - raise IndexError, "n(=%s) must be between 0 and %s"%(n,len(g)-1) + raise IndexError("n(=%s) must be between 0 and %s"%(n,len(g)-1)) return g[n] def gens(self): diff --git a/src/sage/modular/etaproducts.py b/src/sage/modular/etaproducts.py index 81983a9b131..b0568838343 100644 --- a/src/sage/modular/etaproducts.py +++ b/src/sage/modular/etaproducts.py @@ -93,9 +93,9 @@ def __init__(self, level): try: level = ZZ(level) except TypeError: - raise TypeError, "Level (=%s) must be a positive integer" % level + raise TypeError("Level (=%s) must be a positive integer" % level) if (level < 1): - raise ValueError, "Level (=%s) must be a positive integer" % level + raise ValueError("Level (=%s) must be a positive integer" % level) self._N = level def __reduce__(self): @@ -385,7 +385,7 @@ def __init__(self, parent, rdict): for d in rdict.keys(): if N % d: - raise ValueError, "%s does not divide %s" % (d, N) + raise ValueError("%s does not divide %s" % (d, N)) for d in rdict.keys(): if rdict[d] == 0: @@ -397,13 +397,13 @@ def __init__(self, parent, rdict): prod *= (N/d)**rdict[d] if sumR != 0: - raise ValueError, "sum r_d (=%s) is not 0" % sumR + raise ValueError("sum r_d (=%s) is not 0" % sumR) if (sumDR % 24) != 0: - raise ValueError, "sum d r_d (=%s) is not 0 mod 24" % sumDR + raise ValueError("sum d r_d (=%s) is not 0 mod 24" % sumDR) if (sumNoverDr % 24) != 0: - raise ValueError, "sum (N/d) r_d (=%s) is not 0 mod 24" % sumNoverDr + raise ValueError("sum (N/d) r_d (=%s) is not 0 mod 24" % sumNoverDr) if not is_square(prod): - raise ValueError, "product (N/d)^(r_d) (=%s) is not a square" % prod + raise ValueError("product (N/d)^(r_d) (=%s) is not a square" % prod) self._sumDR = sumDR # this is useful to have around self._rdict = rdict @@ -583,9 +583,9 @@ def order_at_cusp(self, cusp): -1 """ if not isinstance(cusp, CuspFamily): - raise TypeError, "Argument (=%s) should be a CuspFamily" % cusp + raise TypeError("Argument (=%s) should be a CuspFamily" % cusp) if cusp.level() != self.level(): - raise ValueError, "Cusp not on right curve!" + raise ValueError("Cusp not on right curve!") return 1/ZZ(24)/gcd(cusp.width(), self.level()//cusp.width()) * sum( [ell*self.r(ell)/cusp.width() * (gcd(cusp.width(), self.level()//ell))**2 for ell in self._keys] ) def divisor(self): @@ -673,9 +673,9 @@ def num_cusps_of_width(N, d): assert d>0 assert ((N % d) == 0) except TypeError: - raise TypeError, "N and d must be integers" + raise TypeError("N and d must be integers") except AssertionError: - raise AssertionError, "N and d must be positive integers with d|N" + raise AssertionError("N and d must be positive integers with d|N") return euler_phi(gcd(d, N//d)) @@ -698,9 +698,9 @@ def AllCusps(N): N = ZZ(N) assert N>0 except TypeError: - raise TypeError, "N must be an integer" + raise TypeError("N must be an integer") except AssertionError: - raise AssertionError, "N must be positive" + raise AssertionError("N must be positive") c = [] for d in divisors(N): n = num_cusps_of_width(N, d) @@ -736,17 +736,17 @@ def __init__(self, N, width, label = None): N = ZZ(N) assert N>0 except TypeError: - raise TypeError, "N must be an integer" + raise TypeError("N must be an integer") except AssertionError: - raise AssertionError, "N must be positive" + raise AssertionError("N must be positive") self._N = N self._width = width if (N % width): - raise ValueError, "Bad width" + raise ValueError("Bad width") if num_cusps_of_width(N, width) > 1 and label == None: - raise ValueError, "There are %s > 1 cusps of width %s on X_0(%s): specify a label" % (num_cusps_of_width(N,width), width, N) + raise ValueError("There are %s > 1 cusps of width %s on X_0(%s): specify a label" % (num_cusps_of_width(N,width), width, N)) if num_cusps_of_width(N, width) == 1 and label != None: - raise ValueError, "There is only one cusp of width %s on X_0(%s): no need to specify a label" % (width, N) + raise ValueError("There is only one cusp of width %s on X_0(%s): no need to specify a label" % (width, N)) self.label = label def width(self): @@ -920,7 +920,7 @@ def eta_poly_relations(eta_elements, degree, labels=['x1','x2'], verbose=False): [x1^3*x2 - 13*x1^3 - 4*x1^2*x2 - 4*x1*x2 - x2^2 + x2] """ if len(eta_elements) > 2: - raise NotImplementedError, "Don't know how to find relations between more than two elements" + raise NotImplementedError("Don't know how to find relations between more than two elements") eta1, eta2 = eta_elements @@ -937,9 +937,9 @@ def eta_poly_relations(eta_elements, degree, labels=['x1','x2'], verbose=False): newgrob = _eta_relations_helper(eta1, eta2, degree, m+5, labels, verbose) if oldgrob != newgrob: if verbose: - raise ArithmeticError, "Answers different!" + raise ArithmeticError("Answers different!") else: - raise ArithmeticError, "Check: answers different!" + raise ArithmeticError("Check: answers different!") return newgrob def _eta_relations_helper(eta1, eta2, degree, qexp_terms, labels, verbose): diff --git a/src/sage/modular/hecke/algebra.py b/src/sage/modular/hecke/algebra.py index cf4566f6033..fe68f649785 100644 --- a/src/sage/modular/hecke/algebra.py +++ b/src/sage/modular/hecke/algebra.py @@ -206,7 +206,7 @@ def __init__(self, M): Full Hecke algebra acting on Cuspidal subspace of dimension 1 of Modular Forms space of dimension 2 for Modular Group SL(2,Z) of weight 12 over Rational Field """ if not module.is_HeckeModule(M): - raise TypeError, "M (=%s) must be a HeckeModule"%M + raise TypeError("M (=%s) must be a HeckeModule"%M) self.__M = M sage.rings.commutative_algebra.CommutativeAlgebra.__init__(self, M.base_ring()) @@ -321,11 +321,11 @@ def __call__(self, x, check=True): A = self.matrix_space()(x) if check: if not A.is_scalar(): - raise NotImplementedError, "Membership testing for '%s' not implemented" % self + raise NotImplementedError("Membership testing for '%s' not implemented" % self) return hecke_operator.HeckeAlgebraElement_matrix(self, A) except TypeError: - raise TypeError, "Don't know how to construct an element of %s from %s" % (self, x) + raise TypeError("Don't know how to construct an element of %s from %s" % (self, x)) def _coerce_impl(self, x): r""" @@ -744,7 +744,7 @@ def hecke_operator(self, n): """ n = int(n) if arith.gcd(self.module().level(), n) != 1: - raise IndexError, "Hecke operator T_%s not defined in the anemic Hecke algebra"%n + raise IndexError("Hecke operator T_%s not defined in the anemic Hecke algebra"%n) return self.module()._hecke_operator_class()(self, n) def is_anemic(self): diff --git a/src/sage/modular/hecke/ambient_module.py b/src/sage/modular/hecke/ambient_module.py index affb3d68b99..f68aa7e4f69 100644 --- a/src/sage/modular/hecke/ambient_module.py +++ b/src/sage/modular/hecke/ambient_module.py @@ -74,7 +74,7 @@ def __init__(self, base_ring, rank, level, weight): """ rank = sage.rings.all.Integer(rank) if rank < 0: - raise ValueError, "rank (=%s) must be nonnegative"%rank + raise ValueError("rank (=%s) must be nonnegative"%rank) self.__rank = rank module.HeckeModule_free_module.__init__(self, base_ring, level, weight) @@ -111,10 +111,10 @@ def __add__(self, other): TypeError: other (=3) must be a Hecke module. """ if not isinstance(other, module.HeckeModule_free_module): - raise TypeError, "other (=%s) must be a Hecke module."%other + raise TypeError("other (=%s) must be a Hecke module."%other) if other.ambient_hecke_module() == self: return self - raise ArithmeticError, "Sum only defined for subspaces of a common ambient Hecke module." + raise ArithmeticError("Sum only defined for subspaces of a common ambient Hecke module.") def _repr_(self): r""" @@ -385,15 +385,15 @@ def degeneracy_map(self, codomain, t=1): else: err = True if err: - raise ValueError, ("The level of self (=%s) must be a divisor or multiple of " + \ + raise ValueError(("The level of self (=%s) must be a divisor or multiple of " + \ "level (=%s), and t (=%s) must be a divisor of the quotient.")%\ - (self.level(), level, t) + (self.level(), level, t)) eps = self.character() if not (eps is None) and level % eps.conductor() != 0: - raise ArithmeticError, "The conductor of the character of this space " + \ + raise ArithmeticError("The conductor of the character of this space " + \ "(=%s) must be divisible by the level (=%s)."%\ - (eps.conductor(), level) + (eps.conductor(), level)) if M is None: M = self.hecke_module_of_level(level) @@ -477,7 +477,7 @@ def fcp(self, n, var='x'): """ n = int(n) if n <= 0: - raise ArithmeticError, "n (=%s) must be positive"%n + raise ArithmeticError("n (=%s) must be positive"%n) return self.hecke_operator(n).fcp(var) def free_module(self): @@ -596,9 +596,9 @@ def intersection(self, other): 1 """ if not isinstance(other, module.HeckeModule_free_module): - raise TypeError, "other (=%s) must be a Hecke module."%other + raise TypeError("other (=%s) must be a Hecke module."%other) if self.ambient_hecke_module() != other.ambient_hecke_module(): - raise ArithmeticError, "Intersection only defined for subspaces of a common ambient Hecke module." + raise ArithmeticError("Intersection only defined for subspaces of a common ambient Hecke module.") return other # since self is ambient, so the intersection must equal other. def is_ambient(self): @@ -694,7 +694,7 @@ def is_submodule(self, V): True """ if not isinstance(V, module.HeckeModule_free_module): - raise TypeError, "V must be a Hecke module" + raise TypeError("V must be a Hecke module") if not V.is_ambient(): return False return V.ambient_hecke_module() == self @@ -772,7 +772,7 @@ def new_submodule(self, p=None): D = arith.prime_divisors(N) else: if N % p != 0: - raise ValueError, "p must divide the level." + raise ValueError("p must divide the level.") D = [p] for q in D: # Here we are only using degeneracy *lowering* maps, so it is fine @@ -884,7 +884,7 @@ def old_submodule(self, p=None): D = arith.prime_divisors(N) else: if N % p != 0: - raise ValueError, "p must divide the level." + raise ValueError("p must divide the level.") D = [p] for q in D: @@ -1001,7 +1001,7 @@ def submodule_generated_by_images(self, M): for t in D: d = M.degeneracy_map(self, t) if d.codomain() != self: - raise ArithmeticError, "incompatible spaces of modular symbols" + raise ArithmeticError("incompatible spaces of modular symbols") S += d.image() if self.is_full_hecke_module(compute=False): diff --git a/src/sage/modular/hecke/element.py b/src/sage/modular/hecke/element.py index 6213aa84acf..c51e76a49be 100644 --- a/src/sage/modular/hecke/element.py +++ b/src/sage/modular/hecke/element.py @@ -101,7 +101,7 @@ def _compute_element(self): # The main reason for this is it allows for lazy constructors who # compute the representation of an element (e.g., a q-expansion) in # terms of the basis only when needed. - raise NotImplementedError, "_compute_element *must* be defined in the derived class if element is set to None in constructor" + raise NotImplementedError("_compute_element *must* be defined in the derived class if element is set to None in constructor") def element(self): """ diff --git a/src/sage/modular/hecke/hecke_operator.py b/src/sage/modular/hecke/hecke_operator.py index 60a75e42c46..561373f2877 100644 --- a/src/sage/modular/hecke/hecke_operator.py +++ b/src/sage/modular/hecke/hecke_operator.py @@ -73,7 +73,7 @@ def __init__(self, parent): Generic element of a structure """ if not algebra.is_HeckeAlgebra(parent): - raise TypeError, "parent (=%s) must be a Hecke algebra"%parent + raise TypeError("parent (=%s) must be a Hecke algebra"%parent) sage.algebras.algebra_element.AlgebraElement.__init__(self, parent) def domain(self): @@ -247,7 +247,7 @@ def apply_sparse(self, x): 24*(1,0) - 5*(1,9) """ if x not in self.domain(): - raise TypeError, "x (=%s) must be in %s"%(x, self.domain()) + raise TypeError("x (=%s) must be in %s"%(x, self.domain())) # Generic implementation which doesn't actually do anything # special regarding sparseness. Override this for speed. T = self.hecke_module_morphism() @@ -441,9 +441,9 @@ def __init__(self, parent, A): if not is_Matrix(A): raise TypeError("A must be a matrix") if not A.base_ring() == self.parent().base_ring(): - raise TypeError, "base ring of matrix (%s) does not match base ring of space (%s)" % (A.base_ring(), self.parent().base_ring()) + raise TypeError("base ring of matrix (%s) does not match base ring of space (%s)" % (A.base_ring(), self.parent().base_ring())) if not A.nrows() == A.ncols() == self.parent().module().rank(): - raise TypeError, "A must be a square matrix of rank %s" % self.parent().module().rank() + raise TypeError("A must be a square matrix of rank %s" % self.parent().module().rank()) self.__matrix = A def __cmp__(self, other): @@ -466,7 +466,7 @@ def __cmp__(self, other): if isinstance(other, HeckeOperator): return cmp(self, other.matrix_form()) else: - raise RuntimeError, "Bug in coercion code" # can't get here. + raise RuntimeError("Bug in coercion code") # can't get here. return cmp(self.__matrix, other.__matrix) def _repr_(self): @@ -604,7 +604,7 @@ def __init__(self, parent, n): """ HeckeAlgebraElement.__init__(self, parent) if not isinstance(n, (int,long,Integer)): - raise TypeError, "n must be an int" + raise TypeError("n must be an int") self.__n = int(n) def __cmp__(self, other): @@ -638,7 +638,7 @@ def __cmp__(self, other): if isinstance(other, HeckeAlgebraElement_matrix): return cmp(self.matrix_form(), other) else: - raise RuntimeError, "Bug in coercion code" # can't get here + raise RuntimeError("Bug in coercion code") # can't get here if self.__n == other.__n: return 0 diff --git a/src/sage/modular/hecke/homspace.py b/src/sage/modular/hecke/homspace.py index 8a5e0448ebf..8eb888b6bb3 100644 --- a/src/sage/modular/hecke/homspace.py +++ b/src/sage/modular/hecke/homspace.py @@ -58,9 +58,9 @@ def __init__(self, X, Y, category = None): True """ if not module.is_HeckeModule(X) or not module.is_HeckeModule(Y): - raise TypeError, "X and Y must be Hecke modules" + raise TypeError("X and Y must be Hecke modules") if X.base_ring() != Y.base_ring(): - raise TypeError, "X and Y must have the same base ring" + raise TypeError("X and Y must have the same base ring") if category is None: category = X.category() sage.categories.homset.HomsetWithBase.__init__(self, X, Y, category = category) @@ -105,7 +105,7 @@ def __call__(self, A, name=''): A._set_parent(self) return A else: - raise TypeError, "unable to coerce A to self" + raise TypeError("unable to coerce A to self") except AttributeError: pass return morphism.HeckeModuleMorphism_matrix(self, A, name) diff --git a/src/sage/modular/hecke/module.py b/src/sage/modular/hecke/module.py index f5b2c50df74..7648af0df6a 100644 --- a/src/sage/modular/hecke/module.py +++ b/src/sage/modular/hecke/module.py @@ -78,7 +78,7 @@ def __init__(self, base_ring, level, category = None): Category of Hecke modules over Rational Field """ if not is_CommutativeRing(base_ring): - raise TypeError, "base_ring must be commutative ring" + raise TypeError("base_ring must be commutative ring") from sage.categories.hecke_modules import HeckeModules default_category = HeckeModules(base_ring) @@ -91,7 +91,7 @@ def __init__(self, base_ring, level, category = None): level = sage.rings.all.ZZ(level) if level <= 0: - raise ValueError, "level (=%s) must be positive"%level + raise ValueError("level (=%s) must be positive"%level) self.__level = level self._hecke_matrices = {} self._diamond_matrices = {} @@ -134,7 +134,7 @@ def __cmp__(self, other): ... NotImplementedError: ... """ - raise NotImplementedError, "Derived class %s should implement __cmp__" % type(self) + raise NotImplementedError("Derived class %s should implement __cmp__" % type(self)) def _compute_hecke_matrix_prime_power(self, p, r, **kwds): r""" @@ -154,7 +154,7 @@ def _compute_hecke_matrix_prime_power(self, p, r, **kwds): # convert input arguments to int's. (p,r) = (int(p), int(r)) if not arith.is_prime(p): - raise ArithmeticError, "p must be a prime" + raise ArithmeticError("p must be a prime") # T_{p^r} := T_p * T_{p^{r-1}} - eps(p)p^{k-1} T_{p^{r-2}}. pow = p**(r-1) if pow not in self._hecke_matrices: @@ -167,7 +167,7 @@ def _compute_hecke_matrix_prime_power(self, p, r, **kwds): Tpr1 = self._hecke_matrices[pow] eps = self.character() if eps is None: - raise NotImplementedError, "either character or _compute_hecke_matrix_prime_power must be overloaded in a derived class" + raise NotImplementedError("either character or _compute_hecke_matrix_prime_power must be overloaded in a derived class") k = self.weight() Tpr2 = self._hecke_matrices[pow/p] return Tp*Tpr1 - eps(p)*(p**(k-1)) * Tpr2 @@ -222,7 +222,7 @@ def _compute_hecke_matrix(self, n, **kwds): """ n = int(n) if n<1: - raise ValueError, "Hecke operator T_%s is not defined."%n + raise ValueError("Hecke operator T_%s is not defined."%n) if n==1: Mat = matrix_space.MatrixSpace(self.base_ring(),self.rank()) return Mat(1) @@ -251,7 +251,7 @@ def _compute_hecke_matrix_prime(self, p, **kwds): ... NotImplementedError: All subclasses must implement _compute_hecke_matrix_prime """ - raise NotImplementedError, "All subclasses must implement _compute_hecke_matrix_prime" + raise NotImplementedError("All subclasses must implement _compute_hecke_matrix_prime") def _compute_diamond_matrix(self, d): r""" @@ -267,7 +267,7 @@ def _compute_diamond_matrix(self, d): ... NotImplementedError: All subclasses without fixed character must implement _compute_diamond_matrix """ - raise NotImplementedError, "All subclasses without fixed character must implement _compute_diamond_matrix" + raise NotImplementedError("All subclasses without fixed character must implement _compute_diamond_matrix") def _hecke_operator_class(self): """ @@ -487,7 +487,7 @@ def rank(self): ... NotImplementedError: Derived subclasses must implement rank """ - raise NotImplementedError, "Derived subclasses must implement rank" + raise NotImplementedError("Derived subclasses must implement rank") def submodule(self, X): r""" @@ -501,7 +501,7 @@ def submodule(self, X): ... NotImplementedError: Derived subclasses should implement submodule """ - raise NotImplementedError, "Derived subclasses should implement submodule" + raise NotImplementedError("Derived subclasses should implement submodule") class HeckeModule_free_module(HeckeModule_generic): @@ -563,7 +563,7 @@ def __getitem__(self, n): n = int(n) D = self.decomposition() if n < 0 or n >= len(D): - raise IndexError, "index (=%s) must be between 0 and %s"%(n, len(D)-1) + raise IndexError("index (=%s) must be between 0 and %s"%(n, len(D)-1)) return D[n] def __hash__(self): @@ -644,7 +644,7 @@ def _eigen_nonzero_element(self, n=1): 4*(1,0) + (2,21) - (11,1) + (11,2) """ if self.rank() == 0: - raise ArithmeticError, "the rank of self must be positive" + raise ArithmeticError("the rank of self must be positive") A = self.ambient_hecke_module() i = self._eigen_nonzero() return A._hecke_image_of_ith_basis_vector(n, i) @@ -675,9 +675,9 @@ def _element_eigenvalue(self, x, name='alpha'): 1 """ if not element.is_HeckeModuleElement(x): - raise TypeError, "x must be a Hecke module element." + raise TypeError("x must be a Hecke module element.") if not x in self.ambient_hecke_module(): - raise ArithmeticError, "x must be in the ambient Hecke module." + raise ArithmeticError("x must be in the ambient Hecke module.") v = self.dual_eigenvector(names=name) return v.dot_product(x.element()) @@ -832,7 +832,7 @@ def atkin_lehner_operator(self, d=None): d = self.level() d = int(d) if self.level() % d != 0: - raise ArithmeticError, "d (=%s) must be a divisor of the level (=%s)"%(d,self.level()) + raise ArithmeticError("d (=%s) must be a divisor of the level (=%s)"%(d,self.level())) N = self.level() for p, e in arith.factor(d): @@ -971,7 +971,7 @@ def decomposition(self, bound=None, anemic=True, height_guess=1, sort_by_basis = ] """ if not isinstance(anemic, bool): - raise TypeError, "anemic must be of type bool." + raise TypeError("anemic must be of type bool.") key = (bound, anemic) @@ -1122,7 +1122,7 @@ def dual_eigenvector(self, names='alpha', lift=True, nz=None): self.__dual_eigenvector = {} if not self.is_simple(): - raise ArithmeticError, "self must be simple" + raise ArithmeticError("self must be simple") # Find a Hecke operator that acts irreducibly on this space: p = 2 @@ -1263,7 +1263,7 @@ def eigenvalue(self, n, name='alpha'): generalized Bernoulli number). """ if not self.is_simple(): - raise ArithmeticError, "self must be simple" + raise ArithmeticError("self must be simple") n = int(n) try: return self.__eigenvalues[n][name] @@ -1272,7 +1272,7 @@ def eigenvalue(self, n, name='alpha'): except KeyError: pass if n <= 0: - raise IndexError, "n must be a positive integer" + raise IndexError("n must be a positive integer") ev = self.__eigenvalues @@ -1357,7 +1357,7 @@ def hecke_matrix(self, n): """ n = int(n) if n <= 0: - raise IndexError, "n must be positive." + raise IndexError("n must be positive.") if n not in self._hecke_matrices: T = self._compute_hecke_matrix(n) T.set_immutable() @@ -1617,9 +1617,8 @@ def projection(self): except AttributeError: i = self.factor_number() if i == -1: - raise NotImplementedError,\ - "Computation of projection only implemented "+\ - "for decomposition factors." + raise NotImplementedError("Computation of projection only implemented "+\ + "for decomposition factors.") A = self.ambient_hecke_module() B = A.decomposition_matrix_inverse() i = (A.decomposition()).index(self) diff --git a/src/sage/modular/hecke/morphism.py b/src/sage/modular/hecke/morphism.py index b18ba2a2c1d..bb0a7518b0e 100644 --- a/src/sage/modular/hecke/morphism.py +++ b/src/sage/modular/hecke/morphism.py @@ -111,7 +111,7 @@ def __init__(self, parent, A, name=''): True """ if not isinstance(name, str): - raise TypeError, "name must be a string" + raise TypeError("name must be a string") self.__name = name MatrixMorphism.__init__(self, parent, A) diff --git a/src/sage/modular/hecke/submodule.py b/src/sage/modular/hecke/submodule.py index 6cb451d3e1a..7d8e4cffa33 100644 --- a/src/sage/modular/hecke/submodule.py +++ b/src/sage/modular/hecke/submodule.py @@ -78,15 +78,15 @@ def __init__(self, ambient, submodule, dual_free_module=None, check=True): True """ if not isinstance(ambient, ambient_module.AmbientHeckeModule): - raise TypeError, "ambient must be an ambient Hecke module" + raise TypeError("ambient must be an ambient Hecke module") if not sage.modules.free_module.is_FreeModule(submodule): - raise TypeError, "submodule must be a free module" + raise TypeError("submodule must be a free module") if not submodule.is_submodule(ambient.free_module()): - raise ValueError, "submodule must be a submodule of the ambient free module" + raise ValueError("submodule must be a submodule of the ambient free module") if check: if not ambient._is_hecke_equivariant_free_module(submodule): - raise ValueError, "The submodule must be invariant under all Hecke operators." + raise ValueError("The submodule must be invariant under all Hecke operators.") self.__ambient = ambient self.__submodule = submodule @@ -94,9 +94,9 @@ def __init__(self, ambient, submodule, dual_free_module=None, check=True): ambient.base_ring(), ambient.level(), ambient.weight()) if not (dual_free_module is None): if not sage.modules.free_module.is_FreeModule(dual_free_module): - raise TypeError, "dual_free_module must be a free module" + raise TypeError("dual_free_module must be a free module") if dual_free_module.rank () != submodule.rank(): - raise ArithmeticError, "dual_free_module must have the same rank as submodule" + raise ArithmeticError("dual_free_module must have the same rank as submodule") self.dual_free_module.set_cache(dual_free_module) @@ -128,9 +128,9 @@ def __add__(self, other): Modular Forms subspace of dimension 6 of Modular Forms space of dimension 6 for Congruence Subgroup Gamma0(4) of weight 10 over Rational Field """ if not isinstance(other, module.HeckeModule_free_module): - raise TypeError, "other (=%s) must be a Hecke module."%other + raise TypeError("other (=%s) must be a Hecke module."%other) if self.ambient() != other.ambient(): - raise ArithmeticError, "Sum only defined for submodules of a common ambient space." + raise ArithmeticError("Sum only defined for submodules of a common ambient space.") if other.is_ambient(): return other # Neither is ambient @@ -158,7 +158,7 @@ def __call__(self, x, check=True): z = self.ambient_hecke_module()(x) if check: if not z.element() in self.__submodule: - raise TypeError, "x does not coerce to an element of this Hecke module" + raise TypeError("x does not coerce to an element of this Hecke module") return z def __cmp__(self, other): @@ -288,9 +288,9 @@ def _set_dual_free_module(self, V): sage: S._set_dual_free_module(S) """ if V.degree() != self.ambient_hecke_module().rank(): - raise ArithmeticError, "The degree of V must equal the rank of the ambient space." + raise ArithmeticError("The degree of V must equal the rank of the ambient space.") if V.rank() != self.rank(): - raise ArithmeticError, "The rank of V must equal the rank of self." + raise ArithmeticError("The rank of V must equal the rank of self.") self.dual_free_module.set_cache(V) @@ -393,7 +393,7 @@ def complement(self, bound=None): return C # failed miserably - raise RuntimeError, "Computation of complementary space failed (cut down to rank %s, but should have cut down to rank %s)."%(V.rank(), A.rank()-self.rank()) + raise RuntimeError("Computation of complementary space failed (cut down to rank %s, but should have cut down to rank %s)."%(V.rank(), A.rank()-self.rank())) def degeneracy_map(self, level, t=1): @@ -587,8 +587,8 @@ def dual_free_module(self, bound=None, anemic=True, use_star=True): if V2.rank() == self.rank(): return V2 else: - raise RuntimeError, "Computation of embedded dual vector space failed " + \ - "(cut down to rank %s, but should have cut down to rank %s)."%(V.rank(), self.rank()) + raise RuntimeError("Computation of embedded dual vector space failed " + \ + "(cut down to rank %s, but should have cut down to rank %s)."%(V.rank(), self.rank())) def free_module(self): @@ -645,8 +645,8 @@ def intersection(self, other): 1 """ if self.ambient_hecke_module() != other.ambient_hecke_module(): - raise ArithmeticError, "Intersection only defined for subspaces of"\ - + " a common ambient modular symbols space." + raise ArithmeticError("Intersection only defined for subspaces of"\ + + " a common ambient modular symbols space.") if other.is_ambient(): return self if self.is_ambient(): @@ -905,7 +905,7 @@ def submodule(self, M, Mdual=None, check=True): if check: if not M.is_submodule(self.free_module()): - raise TypeError, "M (=%s) must be a submodule of the free module (=%s) associated to this module."%(M, self.free_module()) + raise TypeError("M (=%s) must be a submodule of the free module (=%s) associated to this module."%(M, self.free_module())) return self.ambient().submodule(M, Mdual, check=check) diff --git a/src/sage/modular/local_comp/smoothchar.py b/src/sage/modular/local_comp/smoothchar.py index 38e11acb562..3e38bea1606 100644 --- a/src/sage/modular/local_comp/smoothchar.py +++ b/src/sage/modular/local_comp/smoothchar.py @@ -1286,7 +1286,7 @@ def extend_character(self, level, chi, x, check=True): """ chi = chi.base_extend(self.base_ring()) if chi.level() > level: - raise ValueError, "Level of extended character cannot be smaller than level of character of Qp" + raise ValueError("Level of extended character cannot be smaller than level of character of Qp") # check it makes sense e = (self.prime() + 1) * (self.prime()**(level - 1)) @@ -1572,7 +1572,7 @@ def discrete_log(self, level, x): True """ x = self.number_field().coerce(x) - if x == 0: raise ValueError, "cannot evaluate at zero" + if x == 0: raise ValueError("cannot evaluate at zero") n1 = x.valuation(self.ideal(1)) x1 = x / self.number_field().gen()**n1 if level == 0: diff --git a/src/sage/modular/modform/ambient.py b/src/sage/modular/modform/ambient.py index f1d4318295f..7e17a359093 100644 --- a/src/sage/modular/modform/ambient.py +++ b/src/sage/modular/modform/ambient.py @@ -105,7 +105,7 @@ def __init__(self, group, weight, base_ring, character=None): True """ if not arithgroup.is_CongruenceSubgroup(group): - raise TypeError, 'group (=%s) must be a congruence subgroup'%group + raise TypeError('group (=%s) must be a congruence subgroup'%group) weight = rings.Integer(weight) if character is None and arithgroup.is_Gamma0(group): @@ -227,7 +227,7 @@ def hecke_module_of_level(self, N): ValueError: N (=9) must be a divisor or a multiple of the level of self (=4) """ if not (N % self.level() == 0 or self.level() % N == 0): - raise ValueError, "N (=%s) must be a divisor or a multiple of the level of self (=%s)" % (N, self.level()) + raise ValueError("N (=%s) must be a divisor or a multiple of the level of self (=%s)" % (N, self.level())) import constructor return constructor.ModularForms(self.group()._new_group_from_level(N), self.weight(), self.base_ring(), prec=self.prec()) @@ -471,7 +471,7 @@ def set_precision(self, n): ] """ if n < 0: - raise ValueError, "n (=%s) must be >= 0"%n + raise ValueError("n (=%s) must be >= 0"%n) self.__prec = rings.Integer(n) #################################################################### @@ -568,7 +568,7 @@ def new_submodule(self, p=None): if not p is None: p = rings.Integer(p) if not p.is_prime(): - raise ValueError, "p (=%s) must be a prime or None."%p + raise ValueError("p (=%s) must be a prime or None."%p) M = self.cuspidal_submodule().new_submodule(p) + self.eisenstein_submodule().new_submodule(p) self.__new_submodule[p] = M return M diff --git a/src/sage/modular/modform/ambient_R.py b/src/sage/modular/modform/ambient_R.py index 3c8b9f1165b..c377ae978b6 100644 --- a/src/sage/modular/modform/ambient_R.py +++ b/src/sage/modular/modform/ambient_R.py @@ -130,5 +130,5 @@ def change_ring(self, R): ValueError: Space cannot be defined over Rational Field """ if not R.has_coerce_map_from(self.__M.base_ring()): - raise ValueError, "Space cannot be defined over %s" % R + raise ValueError("Space cannot be defined over %s" % R) return ModularFormsAmbient_R(self.__M, R) diff --git a/src/sage/modular/modform/ambient_eps.py b/src/sage/modular/modform/ambient_eps.py index 7b6fcf848a9..3a2f262749a 100644 --- a/src/sage/modular/modform/ambient_eps.py +++ b/src/sage/modular/modform/ambient_eps.py @@ -116,12 +116,12 @@ def __init__(self, character, weight=2, base_ring=None): """ if not dirichlet.is_DirichletCharacter(character): - raise TypeError, "character (=%s) must be a Dirichlet character"%character + raise TypeError("character (=%s) must be a Dirichlet character"%character) if base_ring==None: base_ring=character.base_ring() if character.base_ring() != base_ring: character = character.change_ring(base_ring) if base_ring.characteristic() != 0: - raise ValueError, "the base ring must have characteristic 0." + raise ValueError("the base ring must have characteristic 0.") group = arithgroup.Gamma1(character.modulus()) base_ring = character.base_ring() ambient.ModularFormsAmbient.__init__(self, group, weight, base_ring, character) @@ -271,7 +271,7 @@ def hecke_module_of_level(self, N): elif self.level() % N == 0: return constructor.ModularForms(self.character().restrict(N), self.weight(), self.base_ring(), prec=self.prec()) else: - raise ValueError, "N (=%s) must be a divisor or a multiple of the level of self (=%s)" % (N, self.level()) + raise ValueError("N (=%s) must be a divisor or a multiple of the level of self (=%s)" % (N, self.level())) #################################################################### # Computations of Dimensions diff --git a/src/sage/modular/modform/constructor.py b/src/sage/modular/modform/constructor.py index d3691eafc63..d5e5152f4ab 100644 --- a/src/sage/modular/modform/constructor.py +++ b/src/sage/modular/modform/constructor.py @@ -94,17 +94,17 @@ def canonical_parameters(group, level, weight, base_ring): """ weight = rings.Integer(weight) if weight <= 0: - raise NotImplementedError, "weight must be at least 1" + raise NotImplementedError("weight must be at least 1") if isinstance(group, dirichlet.DirichletCharacter): if ( group.level() != rings.Integer(level) ): - raise ValueError, "group.level() and level do not match." + raise ValueError("group.level() and level do not match.") group = group.minimize_base_ring() level = rings.Integer(level) elif arithgroup.is_CongruenceSubgroup(group): if ( rings.Integer(level) != group.level() ): - raise ValueError, "group.level() and level do not match." + raise ValueError("group.level() and level do not match.") # normalize the case of SL2Z if arithgroup.is_SL2Z(group) or \ arithgroup.is_Gamma1(group) and group.level() == rings.Integer(1): @@ -117,14 +117,14 @@ def canonical_parameters(group, level, weight, base_ring): try: m = rings.Integer(group) except TypeError: - raise TypeError, "group of unknown type." + raise TypeError("group of unknown type.") level = rings.Integer(level) if ( m != level ): - raise ValueError, "group and level do not match." + raise ValueError("group and level do not match.") group = arithgroup.Gamma0(m) if not is_CommutativeRing(base_ring): - raise TypeError, "base_ring (=%s) must be a commutative ring"%base_ring + raise TypeError("base_ring (=%s) must be a commutative ring"%base_ring) # it is *very* important to include the level as part of the data # that defines the key, since dirichlet characters of different @@ -336,7 +336,7 @@ def ModularForms(group = 1, # TODO -- implement this # Need to add a lift_to_char_0 function for characters, # and need to still remember eps. - raise NotImplementedError, "currently the character must be over a ring of characteristic 0." + raise NotImplementedError("currently the character must be over a ring of characteristic 0.") eps = eps.minimize_base_ring() if eps.is_trivial(): return ModularForms(eps.modulus(), weight, base_ring, @@ -347,8 +347,7 @@ def ModularForms(group = 1, M = M.base_extend(base_ring) # ambient_R.ModularFormsAmbient_R(M, base_ring) if M is None: - raise NotImplementedError, \ - "computation of requested space of modular forms not defined or implemented" + raise NotImplementedError("computation of requested space of modular forms not defined or implemented") M.set_precision(prec) _cache[key] = weakref.ref(M) @@ -479,11 +478,11 @@ def Newform(identifier, group=None, weight=2, base_ring=rings.QQ, names=None): if isinstance(identifier, str): group, identifier = parse_label(identifier) if weight != 2: - raise ValueError, "Canonical label not implemented for higher weight forms." + raise ValueError("Canonical label not implemented for higher weight forms.") elif base_ring != rings.QQ: - raise ValueError, "Canonical label not implemented except for over Q." + raise ValueError("Canonical label not implemented except for over Q.") elif group is None: - raise ValueError, "Must specify a group or a label." + raise ValueError("Must specify a group or a label.") return Newforms(group, weight, base_ring, names=names)[identifier] @@ -503,7 +502,7 @@ def parse_label(s): """ m = re.match(r'(\d+)([a-z]+)((?:G.*)?)$', s) if not m: - raise ValueError, "Invalid label: %s" % s + raise ValueError("Invalid label: %s" % s) N, order, G = m.groups() N = int(N) index = 0 @@ -515,11 +514,11 @@ def parse_label(s): G = arithgroup.Gamma1(N) elif G[:2] == 'GH': if G[2] != '[' or G[-1] != ']': - raise ValueError, "Invalid congruence subgroup label: %s" % G + raise ValueError("Invalid congruence subgroup label: %s" % G) gens = [int(g.strip()) for g in G[3:-1].split(',')] return arithgroup.GammaH(N, gens) else: - raise ValueError, "Invalid congruence subgroup label: %s" % G + raise ValueError("Invalid congruence subgroup label: %s" % G) return G, index diff --git a/src/sage/modular/modform/cuspidal_submodule.py b/src/sage/modular/modform/cuspidal_submodule.py index fc40ebbbb1b..7b1569b5cdc 100644 --- a/src/sage/modular/modform/cuspidal_submodule.py +++ b/src/sage/modular/modform/cuspidal_submodule.py @@ -103,7 +103,7 @@ def _compute_q_expansion_basis(self, prec): ... NotImplementedError: q-expansion basis not implemented for "Cuspidal subspace of ..." """ - raise NotImplementedError, 'q-expansion basis not implemented for "%s"' % self + raise NotImplementedError('q-expansion basis not implemented for "%s"' % self) def _repr_(self): """ diff --git a/src/sage/modular/modform/eis_series.py b/src/sage/modular/modform/eis_series.py index d7ee18cf6c4..a6507b5d345 100644 --- a/src/sage/modular/modform/eis_series.py +++ b/src/sage/modular/modform/eis_series.py @@ -126,7 +126,7 @@ def eisenstein_series_qexp(k, prec = 10, K=QQ, var='q', normalization='linear'): """ ## we use this to prevent computation if it would fail anyway. if k <= 0 or k % 2 == 1 : - raise ValueError, "k must be positive and even" + raise ValueError("k must be positive and even") a0 = - bernoulli(k) / (2*k) @@ -135,17 +135,17 @@ def eisenstein_series_qexp(k, prec = 10, K=QQ, var='q', normalization='linear'): try: a0fac = K(1/a0den) except ZeroDivisionError: - raise ValueError, "The denominator of -B_k/(2*k) (=%s) must be invertible in the ring %s"%(a0den, K) + raise ValueError("The denominator of -B_k/(2*k) (=%s) must be invertible in the ring %s"%(a0den, K)) elif normalization == 'constant': a0num = a0.numerator() try: a0fac = K(1/a0num) except ZeroDivisionError: - raise ValueError, "The numerator of -B_k/(2*k) (=%s) must be invertible in the ring %s"%(a0num, K) + raise ValueError("The numerator of -B_k/(2*k) (=%s) must be invertible in the ring %s"%(a0num, K)) elif normalization == 'integral': a0fac = None else: - raise ValueError, "Normalization (=%s) must be one of 'linear', 'constant', 'integral'" % normalization + raise ValueError("Normalization (=%s) must be one of 'linear', 'constant', 'integral'" % normalization) R = PowerSeriesRing(K, var) if K == QQ and normalization == 'linear': diff --git a/src/sage/modular/modform/eisenstein_submodule.py b/src/sage/modular/modform/eisenstein_submodule.py index 26a2895b995..c907aab5a90 100644 --- a/src/sage/modular/modform/eisenstein_submodule.py +++ b/src/sage/modular/modform/eisenstein_submodule.py @@ -657,14 +657,14 @@ def cyclotomic_restriction_tower(L,K): x + zeta6 """ if not L.has_coerce_map_from(K): - raise ValueError, "K must be contained in L" + raise ValueError("K must be contained in L") f = L.defining_polynomial() R = K['x'] x = R.gen() g = R(f) h_ls = [ t[0] for t in g.factor() if t[0](L.gen(0)) == 0 ] if len(h_ls) == 0: - raise ValueError, "K (= Q(\zeta_%s)) is not contained in L (= Q(\zeta_%s))"%(K._n(), L._n()) + raise ValueError("K (= Q(\zeta_%s)) is not contained in L (= Q(\zeta_%s))"%(K._n(), L._n())) h = h_ls[0] def z(a): """ diff --git a/src/sage/modular/modform/element.py b/src/sage/modular/modform/element.py index 2fdc749b3e8..f7e2896a255 100644 --- a/src/sage/modular/modform/element.py +++ b/src/sage/modular/modform/element.py @@ -150,9 +150,9 @@ def _ensure_is_compatible(self, other): ArithmeticError: Modular forms must be in the same ambient space. """ if not isinstance(other, ModularForm_abstract): - raise TypeError, "Second argument must be a modular form." + raise TypeError("Second argument must be a modular form.") if self.parent().ambient() != other.parent().ambient(): - raise ArithmeticError, "Modular forms must be in the same ambient space." + raise ArithmeticError("Modular forms must be in the same ambient space.") def __call__(self, x, prec=None): """ @@ -421,7 +421,7 @@ def character(self, compute=True): for g in gens: df = self.parent().diamond_bracket_operator(g)(self) if df != (df[i] / self[i]) * self: - raise ValueError, "Form is not an eigenvector for <%s>" % g + raise ValueError("Form is not an eigenvector for <%s>" % g) vals.append(df[i] / self[i]) return G(vals) @@ -491,7 +491,7 @@ def q_expansion(self, prec=None): prec = self.parent().prec() prec = rings.Integer(prec) if prec < 0: - raise ValueError, "prec (=%s) must be at least 0"%prec + raise ValueError("prec (=%s) must be at least 0"%prec) try: current_prec, f = self.__q_expansion except AttributeError: @@ -576,14 +576,14 @@ def cuspform_lseries(self, prec=53, -1 """ if self.q_expansion().list()[0] !=0: - raise TypeError,"f = %s is not a cusp form"%self + raise TypeError("f = %s is not a cusp form"%self) from sage.lfunctions.all import Dokchitser key = (prec, max_imaginary_part, max_asymp_coeffs) l = self.weight() N = self.level() w = self.atkin_lehner_eigenvalue() if w is None: - raise ValueError, "Form is not an eigenform for Atkin-Lehner" + raise ValueError("Form is not an eigenform for Atkin-Lehner") e = (-1)**(l/2)*w L = Dokchitser(conductor = N, gammaV = [0,1], @@ -626,17 +626,17 @@ def __init__(self, parent, component, names, check=True): """ if check: if not space.is_ModularFormsSpace(parent): - raise TypeError, "parent must be a space of modular forms" + raise TypeError("parent must be a space of modular forms") if not is_ModularSymbolsSpace(component): - raise TypeError, "component must be a space of modular symbols" + raise TypeError("component must be a space of modular symbols") if parent.group() != component.group(): - raise ValueError, "parent and component must be defined by the same congruence subgroup" + raise ValueError("parent and component must be defined by the same congruence subgroup") if parent.weight() != component.weight(): - raise ValueError, "parent and component must have the same weight" + raise ValueError("parent and component must have the same weight") if not component.is_cuspidal(): - raise ValueError, "component must be cuspidal" + raise ValueError("component must be cuspidal") if not component.is_simple(): - raise ValueError, "component must be simple" + raise ValueError("component must be simple") extension_field = component.eigenvalue(1,name=names).parent() if extension_field != parent.base_ring(): # .degree() != 1 and rings.is_NumberField(extension_field): assert extension_field.base_field() == parent.base_ring() @@ -937,7 +937,7 @@ def __init__(self, parent, x, check=True): Modular Forms space of dimension 2 for Congruence Subgroup Gamma0(11) of weight 2 over Rational Field """ if not isinstance(parent, space.ModularFormsSpace): - raise TypeError, "First argument must be an ambient space of modular forms." + raise TypeError("First argument must be an ambient space of modular forms.") element.HeckeModuleElement.__init__(self, parent, x) def _compute_q_expansion(self, prec): @@ -1034,7 +1034,7 @@ def __mul__(self, other): # first ensure the levels are equal if self.level() != other.level(): - raise NotImplementedError, "Cannot multiply forms of different levels" + raise NotImplementedError("Cannot multiply forms of different levels") # find out about characters try: @@ -1094,9 +1094,9 @@ def modform_lseries(self, prec=53, """ a = self.q_expansion(prec).list() if a[0] == 0: - raise TypeError,"f = %s is a cusp form; please use f.cuspform_lseries() instead!"%self + raise TypeError("f = %s is a cusp form; please use f.cuspform_lseries() instead!"%self) if self.level() != 1: - raise TypeError, "f = %s is not a modular form for SL_2(Z)"%self + raise TypeError("f = %s is not a modular form for SL_2(Z)"%self) from sage.lfunctions.all import Dokchitser key = (prec, max_imaginary_part, max_asymp_coeffs) l = self.weight() @@ -1135,8 +1135,8 @@ def atkin_lehner_eigenvalue(self, d=None): try: f = self.parent().atkin_lehner_operator(d)(self) except NotImplementedError: - raise NotImplementedError, "Don't know how to compute Atkin-Lehner matrix acting on this space" \ - + " (try using a newform constructor instead)" + raise NotImplementedError("Don't know how to compute Atkin-Lehner matrix acting on this space" \ + + " (try using a newform constructor instead)") if f == self: return 1 elif f == -self: @@ -1306,14 +1306,14 @@ def __init__(self, parent, vector, t, chi, psi): N = parent.level() K = parent.base_ring() if chi.parent().modulus() != N or psi.parent().modulus() != N: - raise ArithmeticError, "Incompatible moduli" + raise ArithmeticError("Incompatible moduli") if chi.parent().base_ring() != K or psi.parent().base_ring() != K: - raise ArithmeticError, "Incompatible base rings" + raise ArithmeticError("Incompatible base rings") t = int(t) #if not isinstance(t, int): raise TypeError, "weight must be an int" if parent.weight() == 2 and chi.is_trivial() \ and psi.is_trivial() and t==1: - raise ArithmeticError, "If chi and psi are trivial and k=2, then t must be >1." + raise ArithmeticError("If chi and psi are trivial and k=2, then t must be >1.") ModularFormElement.__init__(self, parent, vector) self.__chi = chi self.__psi = psi diff --git a/src/sage/modular/modform/half_integral.py b/src/sage/modular/modform/half_integral.py index 6ee914eca73..6eede485fd3 100644 --- a/src/sage/modular/modform/half_integral.py +++ b/src/sage/modular/modform/half_integral.py @@ -115,13 +115,13 @@ def half_integral_weight_modform_basis(chi, k, prec): """ if chi.modulus() % 16: - raise ValueError, "the character must have modulus divisible by 16" + raise ValueError("the character must have modulus divisible by 16") if not k%2: - raise ValueError, "k (=%s) must be odd"%k + raise ValueError("k (=%s) must be odd"%k) if k < 3: - raise ValueError, "k (=%s) must be at least 3"%k + raise ValueError("k (=%s) must be at least 3"%k) chi = chi.minimize_base_ring() psi = chi.parent()(DirichletGroup(4, chi.base_ring()).gen()) diff --git a/src/sage/modular/modform/hecke_operator_on_qexp.py b/src/sage/modular/modform/hecke_operator_on_qexp.py index d3616057966..0f5570b06de 100644 --- a/src/sage/modular/modform/hecke_operator_on_qexp.py +++ b/src/sage/modular/modform/hecke_operator_on_qexp.py @@ -77,9 +77,9 @@ def hecke_operator_on_qexp(f, n, k, eps = None, eps = DirichletGroup(1, base_ring=ZZ).gen(0) if check: if not (is_PowerSeries(f) or is_ModularFormElement(f)): - raise TypeError, "f (=%s) must be a power series or modular form"%f + raise TypeError("f (=%s) must be a power series or modular form"%f) if not is_DirichletCharacter(eps): - raise TypeError, "eps (=%s) must be a Dirichlet character"%eps + raise TypeError("eps (=%s) must be a Dirichlet character"%eps) k = Integer(k) n = Integer(n) v = [] @@ -207,7 +207,7 @@ def hecke_operator_on_basis(B, n, k, eps=None, Full MatrixSpace of 0 by 0 dense matrices over Cyclotomic Field of order 12 and degree 4 """ if not isinstance(B, (list, tuple)): - raise TypeError, "B (=%s) must be a list or tuple"%B + raise TypeError("B (=%s) must be a list or tuple"%B) if len(B) == 0: if eps is None: R = CyclotomicField(1) @@ -223,7 +223,7 @@ def hecke_operator_on_basis(B, n, k, eps=None, if not is_PowerSeries(x): all_powerseries = False if not all_powerseries: - raise TypeError, "each element of B must be a power series" + raise TypeError("each element of B must be a power series") n = Integer(n) k = Integer(k) prec = (f.prec()-1)//n diff --git a/src/sage/modular/modform/j_invariant.py b/src/sage/modular/modform/j_invariant.py index dd35c3a9a16..9344740deb7 100644 --- a/src/sage/modular/modform/j_invariant.py +++ b/src/sage/modular/modform/j_invariant.py @@ -18,7 +18,7 @@ def j_invariant_qexp(prec=10, K=QQ): q^-1 + q^7 + q^15 + q^31 + q^47 + q^55 + q^71 + q^87 + O(q^100) """ if prec <= -1: - raise ValueError, "the prec must be nonnegative." + raise ValueError("the prec must be nonnegative.") prec += 2 g6 = -504*eisenstein_series_qexp(6, prec, K=QQ) Delta = delta_qexp(prec).change_ring(QQ) diff --git a/src/sage/modular/modform/numerical.py b/src/sage/modular/modform/numerical.py index 382013d5d77..e63cb2dc3bc 100644 --- a/src/sage/modular/modform/numerical.py +++ b/src/sage/modular/modform/numerical.py @@ -100,7 +100,7 @@ def __init__(self, group, weight=2, eps=1e-20, self._weight = Integer(weight) self._tp = tp if self._weight < 2: - raise ValueError, "weight must be at least 2" + raise ValueError("weight must be at least 2") self._eps = eps self._delta = delta @@ -117,7 +117,7 @@ def __cmp__(self, other): 0 """ if not isinstance( other, NumericalEigenforms ): - raise ValueError, "%s is not a space of numerical eigenforms"%other + raise ValueError("%s is not a space of numerical eigenforms"%other) if self.modular_symbols() == other.modular_symbols(): return 0 else: @@ -176,7 +176,7 @@ def modular_symbols(self): M = ModularSymbols(self._group, self._weight, sign=1) if M.base_ring() != QQ: - raise ValueError, "modular forms space must be defined over QQ" + raise ValueError("modular forms space must be defined over QQ") self.__modular_symbols = M return M @@ -395,7 +395,7 @@ def ap(self, p): """ p = Integer(p) if not p.is_prime(): - raise ValueError, "p must be a prime" + raise ValueError("p must be a prime") try: return self._ap[p] except AttributeError: @@ -429,7 +429,7 @@ def eigenvalues(self, primes): primes = [Integer(p) for p in primes] for p in primes: if not p.is_prime(): - raise ValueError, 'each element of primes must be prime.' + raise ValueError('each element of primes must be prime.') phi_x, phi_x_inv, nzp, x_nzp = self._eigendata() B = self._eigenvectors() def phi(y): diff --git a/src/sage/modular/modform/space.py b/src/sage/modular/modform/space.py index 926f37a2f80..e131ca0c51e 100644 --- a/src/sage/modular/modform/space.py +++ b/src/sage/modular/modform/space.py @@ -127,14 +127,14 @@ def __init__(self, group, weight, character, base_ring): print "Modular forms -- under development -- do not trust yet." WARN=False if not arithgroup.is_CongruenceSubgroup(group): - raise TypeError, "group (=%s) must be a congruence subgroup"%group + raise TypeError("group (=%s) must be a congruence subgroup"%group) weight = int(weight) #if not isinstance(weight, int): # raise TypeError, "weight must be an int" if not ((character is None) or isinstance(character, dirichlet.DirichletCharacter)): - raise TypeError, "character must be a Dirichlet character" + raise TypeError("character must be a Dirichlet character") if not isinstance(base_ring, rings.Ring): - raise TypeError, "base_ring must be a ring" + raise TypeError("base_ring must be a ring") self.__sturm_bound = None self.__weight, self.__group, self.__character = weight, group, character hecke.HeckeModule_generic.__init__(self, base_ring, group.level()) @@ -244,7 +244,7 @@ def change_ring(self, R): ... NotImplementedError: This function has not yet been implemented. """ - raise NotImplementedError, "This function has not yet been implemented." + raise NotImplementedError("This function has not yet been implemented.") def weight(self): """ @@ -398,7 +398,7 @@ def __normalize_prec(self, prec): else: prec = rings.Integer(prec) if prec < 0: - raise ValueError, "prec (=%s) must be at least 0"%prec + raise ValueError("prec (=%s) must be at least 0"%prec) return prec def base_extend(self, base_ring): @@ -431,7 +431,7 @@ def base_extend(self, base_ring): ValueError: No coercion defined """ if not base_ring.has_coerce_map_from(self.base_ring()): - raise ValueError, "No coercion defined" + raise ValueError("No coercion defined") else: return self.change_ring(base_ring) @@ -768,7 +768,7 @@ def _compute_q_expansion_basis(self, prec): ... NotImplementedError: this must be implemented in the derived class """ - raise NotImplementedError, "this must be implemented in the derived class" + raise NotImplementedError("this must be implemented in the derived class") def q_echelon_basis(self, prec=None): r""" @@ -843,7 +843,7 @@ def q_integral_basis(self, prec=None): ] """ if not self.base_ring() == rings.QQ: - raise TypeError, "the base ring must be Q" + raise TypeError("the base ring must be Q") prec = self.__normalize_prec(prec) R = rings.PowerSeriesRing(rings.ZZ, name=defaults.DEFAULT_VARIABLE) if prec == 0: @@ -949,9 +949,9 @@ def __add__(self, right): """ from sage.modular.modform.submodule import ModularFormsSubmodule if self.ambient_module() != right.ambient_module(): - raise ArithmeticError, ("Sum of %s and %s not defined because " + \ + raise ArithmeticError(("Sum of %s and %s not defined because " + \ "they do not lie in a common ambient space.")%\ - (self, right) + (self, right)) if self.is_ambient(): return self if right.is_ambient(): return right V = self.free_module() + right.free_module() @@ -1056,7 +1056,7 @@ def _coerce_impl(self, x): ## where Gamma' is contained in Gamma. return self(x.q_expansion(self._q_expansion_module().degree())) - raise TypeError, "no known coercion to modular form" + raise TypeError("no known coercion to modular form") def __call__(self, x, check=True): """ @@ -1153,28 +1153,28 @@ def __call__(self, x, check=True): return self(x.q_expansion(W.degree())) except NotImplementedError: pass - raise TypeError, "unable to coerce x (= %s) into %s"%(x, self) + raise TypeError("unable to coerce x (= %s) into %s"%(x, self)) elif is_PowerSeries(x): if x.prec() == PlusInfinity(): if x == 0: return element.ModularFormElement(self, self.free_module().zero_element()) else: - raise TypeError, "unable to create modular form from exact non-zero polynomial" + raise TypeError("unable to create modular form from exact non-zero polynomial") W = self._q_expansion_module() if W.degree() <= x.prec(): try: x_potential = W.coordinates(x.padded_list(W.degree())) except ArithmeticError: - raise ValueError, "q-expansion does not correspond to a form in self" + raise ValueError("q-expansion does not correspond to a form in self") x_potential = self.free_module().linear_combination_of_basis(x_potential) x_potential = element.ModularFormElement(self, x_potential) for i in range(int(W.degree()), x.prec()): if x_potential[i] != x[i]: - raise ValueError, "q-expansion does not correspond to a form in self" + raise ValueError("q-expansion does not correspond to a form in self") return x_potential else: - raise TypeError, "q-expansion needed to at least precision %s"%W.degree() + raise TypeError("q-expansion needed to at least precision %s"%W.degree()) return element.ModularFormElement(self, self.free_module()(x,check)) def __cmp__(self, x): @@ -1425,7 +1425,7 @@ def gen(self, n): try: return self.basis()[int(n)] except IndexError: - raise ValueError, "Generator %s not defined"%n + raise ValueError("Generator %s not defined"%n) def gens(self): """ @@ -1654,7 +1654,7 @@ def new_submodule(self, p=None): ... NotImplementedError: computation of new submodule not yet implemented """ - raise NotImplementedError, "computation of new submodule not yet implemented" + raise NotImplementedError("computation of new submodule not yet implemented") def new_subspace(self, p=None): """ @@ -1684,7 +1684,7 @@ def eisenstein_series(self): ... NotImplementedError: computation of Eisenstein series in this space not yet implemented """ - raise NotImplementedError, "computation of Eisenstein series in this space not yet implemented" + raise NotImplementedError("computation of Eisenstein series in this space not yet implemented") def decomposition(self): """ @@ -1728,7 +1728,7 @@ def newforms(self, names=None): factors = M.cuspidal_subspace().new_subspace().decomposition() large_dims = [ X.dimension() for X in factors if X.dimension() != 1 ] if len(large_dims) > 0 and names is None: - raise ValueError, "Please specify a name to be used when generating names for generators of Hecke eigenvalue fields corresponding to the newforms." + raise ValueError("Please specify a name to be used when generating names for generators of Hecke eigenvalue fields corresponding to the newforms.") elif names is None: # In this case, we don't need a variable name, so insert # something to get passed along below @@ -1886,7 +1886,7 @@ def modular_symbols(self, sign=0): ... NotImplementedError: computation of associated modular symbols space not yet implemented """ - raise NotImplementedError, "computation of associated modular symbols space not yet implemented" + raise NotImplementedError("computation of associated modular symbols space not yet implemented") def find_in_space(self, f, forms=None, prec=None, indep=True): """ @@ -1939,7 +1939,7 @@ def find_in_space(self, f, forms=None, prec=None, indep=True): n = B.degree() else: if not isinstance(forms, (list, tuple)): - raise TypeError, "forms must be a list or tuple" + raise TypeError("forms must be a list or tuple") if prec is None: n = forms[0].parent().prec() else: @@ -1951,7 +1951,7 @@ def find_in_space(self, f, forms=None, prec=None, indep=True): else: B = V.span(w) if is_PowerSeries(f) and f.prec() < n: - raise ValueError, "you need at least %s terms of precision"%n + raise ValueError("you need at least %s terms of precision"%n) x = V(f.padded_list(n)) return B.coordinates(x) diff --git a/src/sage/modular/modform/theta.py b/src/sage/modular/modform/theta.py index a0c580bc61f..22d47bf3172 100644 --- a/src/sage/modular/modform/theta.py +++ b/src/sage/modular/modform/theta.py @@ -44,7 +44,7 @@ def theta2_qexp(prec=10, var='q', K=ZZ, sparse=False): """ prec = Integer(prec) if prec <= 0: - raise ValueError, "prec must be positive" + raise ValueError("prec must be positive") if sparse: v = {} else: @@ -92,7 +92,7 @@ def theta_qexp(prec=10, var='q', K=ZZ, sparse=False): """ prec = Integer(prec) if prec <= 0: - raise ValueError, "prec must be positive" + raise ValueError("prec must be positive") if sparse: v = {} else: diff --git a/src/sage/modular/modform/vm_basis.py b/src/sage/modular/modform/vm_basis.py index 025d57744cf..6fc80ce52ad 100644 --- a/src/sage/modular/modform/vm_basis.py +++ b/src/sage/modular/modform/vm_basis.py @@ -125,7 +125,7 @@ def victor_miller_basis(k, prec=10, cusp_only=False, var='q'): if k%2 == 1 or k==2: return Sequence([]) elif k < 0: - raise ValueError, "k must be non-negative" + raise ValueError("k must be non-negative") elif k == 0: return Sequence([PowerSeriesRing(ZZ,var)(1).add_bigoh(prec)], cr=True) e = k.mod(12) @@ -230,7 +230,7 @@ def _delta_poly(prec=10): 7 0 1 -24 252 -1472 4830 -6048 """ if prec <= 0: - raise ValueError, "prec must be positive" + raise ValueError("prec must be positive") v = [0] * prec # Let F = \sum_{n >= 0} (-1)^n (2n+1) q^(floor(n(n+1)/2)). diff --git a/src/sage/modular/modsym/boundary.py b/src/sage/modular/modsym/boundary.py index 5d006016dcd..e7c2334a51e 100644 --- a/src/sage/modular/modsym/boundary.py +++ b/src/sage/modular/modsym/boundary.py @@ -322,12 +322,12 @@ def __init__(self, """ weight = int(weight) if weight <= 1: - raise ArithmeticError, "weight must be at least 2" + raise ArithmeticError("weight must be at least 2") if not arithgroup.is_CongruenceSubgroup(group): - raise TypeError, "group must be a congruence subgroup" + raise TypeError("group must be a congruence subgroup") sign = int(sign) if not isinstance(base_ring, rings.Ring) and rings.is_CommutativeRing(base_ring): - raise TypeError, "base_ring must be a commutative ring" + raise TypeError("base_ring must be a commutative ring") if character == None and arithgroup.is_Gamma0(group): character = dirichlet.TrivialCharacter(group.level(), base_ring) (self.__group, self.__weight, self.__character, @@ -448,7 +448,7 @@ def gen(self, i=0): [1/3] """ if i >= len(self._known_gens) or i < 0: - raise ValueError, "only %s generators known for %s"%(len(self._known_gens), self) + raise ValueError("only %s generators known for %s"%(len(self._known_gens), self)) return BoundarySpaceElement(self, {i:1}) def __len__(self): @@ -569,10 +569,10 @@ def __call__(self, x): elif element.is_ModularSymbolsElement(x): M = x.parent() if not isinstance(M, ambient.ModularSymbolsAmbient): - raise TypeError, "x (=%s) must be an element of a space of modular symbols of type ModularSymbolsAmbient"%x + raise TypeError("x (=%s) must be an element of a space of modular symbols of type ModularSymbolsAmbient"%x) if M.level() != self.level(): - raise TypeError, "x (=%s) must have level %s but has level %s"%( - x, self.level(), M.level()) + raise TypeError("x (=%s) must have level %s but has level %s"%( + x, self.level(), M.level())) S = x.manin_symbol_rep() if len(S) == 0: return self(0) @@ -582,7 +582,7 @@ def __call__(self, x): y = dict([(i,x[i]) for i in xrange(len(x))]) return BoundarySpaceElement(self, y) - raise TypeError, "Coercion of %s (of type %s) into %s not (yet) defined."%(x, type(x), self) + raise TypeError("Coercion of %s (of type %s) into %s not (yet) defined."%(x, type(x), self)) def _repr_(self): """ @@ -651,9 +651,9 @@ def __init__(self, level, weight, sign, F): sign = int(sign) weight = int(weight) if not sign in [-1,0,1]: - raise ArithmeticError, "sign must be an int in [-1,0,1]" + raise ArithmeticError("sign must be an int in [-1,0,1]") if level <= 0: - raise ArithmeticError, "level must be positive" + raise ArithmeticError("level must be positive") BoundarySpace.__init__(self, weight = weight, group = arithgroup.Gamma0(level), @@ -794,9 +794,9 @@ def __init__(self, level, weight, sign, F): level = int(level) sign = int(sign) if not sign in [-1,0,1]: - raise ArithmeticError, "sign must be an int in [-1,0,1]" + raise ArithmeticError("sign must be an int in [-1,0,1]") if level <= 0: - raise ArithmeticError, "level must be positive" + raise ArithmeticError("level must be positive") BoundarySpace.__init__(self, weight = weight, @@ -996,7 +996,7 @@ def __init__(self, group, weight, sign, F): """ sign = int(sign) if not sign in [-1,0,1]: - raise ArithmeticError, "sign must be an int in [-1,0,1]" + raise ArithmeticError("sign must be an int in [-1,0,1]") BoundarySpace.__init__(self, weight = weight, @@ -1217,9 +1217,9 @@ def __init__(self, eps, weight, sign=0): sign = int(sign) self.__eps = eps if not sign in [-1,0,1]: - raise ArithmeticError, "sign must be an int in [-1,0,1]" + raise ArithmeticError("sign must be an int in [-1,0,1]") if level <= 0: - raise ArithmeticError, "level must be positive" + raise ArithmeticError("level must be positive") BoundarySpace.__init__(self, weight = weight, group = arithgroup.Gamma1(level), diff --git a/src/sage/modular/modsym/element.py b/src/sage/modular/modsym/element.py index a505bb3b988..7d68f41f128 100644 --- a/src/sage/modular/modsym/element.py +++ b/src/sage/modular/modsym/element.py @@ -76,7 +76,7 @@ def set_modsym_print_mode(mode="manin"): """ mode = str(mode).lower() if not (mode in ['manin', 'modular', 'vector']): - raise ValueError, "mode must be one of 'manin', 'modular', or 'vector'" + raise ValueError("mode must be one of 'manin', 'modular', or 'vector'") global _print_mode _print_mode = mode @@ -113,11 +113,11 @@ def __init__(self, parent, x, check=True): """ if check: if not isinstance(parent, ambient.ModularSymbolsAmbient): - raise TypeError, "parent must be an ambient space of modular symbols." + raise TypeError("parent must be an ambient space of modular symbols.") if not isinstance(x, sage.modules.free_module_element.FreeModuleElement): - raise TypeError, "x must be a free module element." + raise TypeError("x must be a free module element.") if x.degree() != parent.degree(): - raise TypeError, "x (of degree %s) must be of degree the same as the degree of the parent (of degree %s)."%(x.degree(), parent.degree()) + raise TypeError("x (of degree %s) must be of degree the same as the degree of the parent (of degree %s)."%(x.degree(), parent.degree())) hecke.HeckeModuleElement.__init__(self, parent, x) def __cmp__(self, other): diff --git a/src/sage/modular/modsym/hecke_operator.py b/src/sage/modular/modsym/hecke_operator.py index acf665483ed..2c62d6b2aa5 100644 --- a/src/sage/modular/modsym/hecke_operator.py +++ b/src/sage/modular/modsym/hecke_operator.py @@ -33,7 +33,7 @@ def apply_sparse(self, x): TypeError: x (=[X^2,(0,1)]) must be in Modular Symbols space of dimension 4 for Gamma_0(17) of weight 4 with sign -1 over Rational Field """ if x not in self.domain(): - raise TypeError, "x (=%s) must be in %s"%(x, self.domain()) + raise TypeError("x (=%s) must be in %s"%(x, self.domain())) # old version just to check for correctness #return self.hecke_module_morphism()(x) diff --git a/src/sage/modular/modsym/manin_symbols.py b/src/sage/modular/modsym/manin_symbols.py index eb40ec066e1..7e861b1be1f 100644 --- a/src/sage/modular/modsym/manin_symbols.py +++ b/src/sage/modular/modsym/manin_symbols.py @@ -181,7 +181,7 @@ def apply(self, j, X): NotImplementedError: Only implemented in derived classes """ - raise NotImplementedError, "Only implemented in derived classes" + raise NotImplementedError("Only implemented in derived classes") def _apply_S_only_0pm1(self): """ @@ -217,7 +217,7 @@ def apply_S(self, j): ... NotImplementedError: Only implemented in derived classes """ - raise NotImplementedError, "Only implemented in derived classes" + raise NotImplementedError("Only implemented in derived classes") def apply_I(self, j): """ @@ -234,7 +234,7 @@ def apply_I(self, j): ... NotImplementedError: Only implemented in derived classes """ - raise NotImplementedError, "Only implemented in derived classes" + raise NotImplementedError("Only implemented in derived classes") def apply_T(self, j): """ @@ -251,7 +251,7 @@ def apply_T(self, j): ... NotImplementedError: Only implemented in derived classes """ - raise NotImplementedError, "Only implemented in derived classes" + raise NotImplementedError("Only implemented in derived classes") def apply_TT(self, j): """ @@ -268,7 +268,7 @@ def apply_TT(self, j): ... NotImplementedError: Only implemented in derived classes """ - raise NotImplementedError, "Only implemented in derived classes" + raise NotImplementedError("Only implemented in derived classes") def index(self, x): """ @@ -382,7 +382,7 @@ def normalize(self, x): sage: m.normalize((0,6,7)) # not implemented in base class """ - raise NotImplementedError, "Only implemented in derived classes" + raise NotImplementedError("Only implemented in derived classes") def weight(self): """ @@ -1547,11 +1547,11 @@ def __init__(self, parent, t): """ if not isinstance(parent, ManinSymbolList): - raise TypeError, "parent (=%s) must be of type ManinSymbolList."%( - parent) + raise TypeError("parent (=%s) must be of type ManinSymbolList."%( + parent)) self.__parent = parent if not isinstance(t, tuple): - raise TypeError, "t (=%s) must be of type tuple."%t + raise TypeError("t (=%s) must be of type tuple."%t) self.__t = t def tuple(self): @@ -1814,7 +1814,7 @@ def endpoints(self, N=None): else: N=int(N) if N < 1: - raise ArithmeticError, "N must be positive" + raise ArithmeticError("N must be positive") a,b,c,d = self.lift_to_sl2z() return cusps.Cusp(b,d), cusps.Cusp(a,c) diff --git a/src/sage/modular/modsym/modsym.py b/src/sage/modular/modsym/modsym.py index f0a118d1b35..5e3d615dd78 100644 --- a/src/sage/modular/modsym/modsym.py +++ b/src/sage/modular/modsym/modsym.py @@ -109,11 +109,11 @@ def canonical_parameters(group, weight, sign, base_ring): """ sign = rings.Integer(sign) if not (sign in [-1,0,1]): - raise ValueError, "sign must be -1, 0, or 1" + raise ValueError("sign must be -1, 0, or 1") weight = rings.Integer(weight) if weight <= 1: - raise ValueError, "the weight must be at least 2" + raise ValueError("the weight must be at least 2") if isinstance(group, (int, rings.Integer)): group = arithgroup.Gamma0(group) @@ -134,10 +134,10 @@ def canonical_parameters(group, weight, sign, base_ring): if base_ring is None: base_ring = rational_field.RationalField() if not is_CommutativeRing(base_ring): - raise TypeError, "base_ring (=%s) must be a commutative ring"%base_ring + raise TypeError("base_ring (=%s) must be a commutative ring"%base_ring) if not base_ring.is_field(): - raise TypeError, "(currently) base_ring (=%s) must be a field"%base_ring + raise TypeError("(currently) base_ring (=%s) must be a field"%base_ring) return group, weight, sign, base_ring @@ -367,7 +367,7 @@ def ModularSymbols(group = 1, weight, sign, base_ring, custom_init=custom_init) if M is None: - raise NotImplementedError, "computation of requested space of modular symbols not defined or implemented" + raise NotImplementedError("computation of requested space of modular symbols not defined or implemented") if use_cache: _cache[key] = weakref.ref(M) diff --git a/src/sage/modular/modsym/p1list_nf.py b/src/sage/modular/modsym/p1list_nf.py index d7cef23f8cd..4014fa682a9 100644 --- a/src/sage/modular/modsym/p1list_nf.py +++ b/src/sage/modular/modsym/p1list_nf.py @@ -190,22 +190,22 @@ def __init__(self, N, c, d=None, check=True): c1 = R(c[0]) d1 = R(c[1]) else: - raise ValueError, "Cannot change level of an MSymbol" + raise ValueError("Cannot change level of an MSymbol") else: try: c1 = R(c[0]) d1 = R(c[1]) except (ValueError, TypeError): - raise TypeError, "Unable to create a Manin symbol from %s"%c + raise TypeError("Unable to create a Manin symbol from %s"%c) else: try: c1 = R(c) d1 = R(d) except (ValueError, TypeError): - raise TypeError, "Unable to create a Manin symbol from (%s, %s)"%(c, d) + raise TypeError("Unable to create a Manin symbol from (%s, %s)"%(c, d)) if check: if (c1.is_zero() and d1.is_zero()) or not N.is_coprime(k.ideal(c1, d1)): - raise ValueError, "(%s, %s) is not an element of P1(R/N)."%(c1, d1) + raise ValueError("(%s, %s) is not an element of P1(R/N)."%(c1, d1)) self.__c, self.__d = (c1, d1) def __repr__(self): @@ -254,7 +254,7 @@ def __cmp__(self, other): True """ if not isinstance(other, MSymbol): - raise ValueError, "You can only compare with another M-symbol" + raise ValueError("You can only compare with another M-symbol") return cmp([self.__c.list(), self.__d.list()], [other.__c.list(), other.__d.list()]) @@ -520,7 +520,7 @@ def __cmp__(self, other): True """ if not isinstance(other, P1NFList): - raise ValueError, "You can only compare with another P1NFList" + raise ValueError("You can only compare with another P1NFList") return cmp(self.__N, other.__N) def __getitem__(self, n): @@ -635,7 +635,7 @@ def normalize(self, c, d=None, with_scalar=False): try: c = MSymbol(self.__N, c) # check that c is an MSymbol except ValueError: # catch special case of wrong level - raise ValueError, "The MSymbol is of a different level" + raise ValueError("The MSymbol is of a different level") return c.normalize(with_scalar) return MSymbol(self.N(), c, d).normalize(with_scalar) @@ -718,7 +718,7 @@ def index(self, c, d=None, with_scalar=False): try: c = MSymbol(self.__N, c) # check that c is an MSymbol except ValueError: # catch special case of wrong level - raise ValueError, "The MSymbol is of a different level" + raise ValueError("The MSymbol is of a different level") if with_scalar: u, norm_c = c.normalize(with_scalar=True) else: @@ -769,7 +769,7 @@ def index_of_normalized_pair(self, c, d=None): try: c = MSymbol(self.__N, c) # check that c is an MSymbol except ValueError: # catch special case of wrong level - raise ValueError, "The MSymbol is of a different level" + raise ValueError("The MSymbol is of a different level") t, i = search(self.__list, c) else: t, i = search(self.__list, MSymbol(self.__N, c, d)) @@ -1088,9 +1088,9 @@ def lift_to_sl2_Ok(N, c, d): k = N.number_field() #check the input if c.is_zero() and d.is_zero(): - raise ValueError, "Cannot lift (%s, %s) to an element of Sl2(Ok)."%(c, d) + raise ValueError("Cannot lift (%s, %s) to an element of Sl2(Ok)."%(c, d)) if not N.is_coprime(k.ideal(c, d)): - raise ValueError, "<%s> + <%s> and the %s are not coprime."%(c, d, N) + raise ValueError("<%s> + <%s> and the %s are not coprime."%(c, d, N)) #a few special cases if c - 1 in N: return [k(0), k(-1), 1, d] @@ -1189,7 +1189,7 @@ def psi(N): 26 """ if not N.is_integral(): - raise ValueError, "psi only defined for integral ideals" + raise ValueError("psi only defined for integral ideals") from sage.misc.misc import prod return prod([(np+1)*np**(e-1) \ diff --git a/src/sage/modular/modsym/relation_matrix.py b/src/sage/modular/modsym/relation_matrix.py index ce54ecfe361..5346651bd51 100644 --- a/src/sage/modular/modsym/relation_matrix.py +++ b/src/sage/modular/modsym/relation_matrix.py @@ -106,7 +106,7 @@ def modS_relations(syms): set([((3, 1), (6, 1)), ((0, 1), (5, 1)), ((0, 1), (2, 1)), ((3, 1), (4, 1)), ((6, 1), (7, 1)), ((1, 1), (2, 1)), ((1, 1), (5, 1)), ((4, 1), (7, 1))]) """ if not isinstance(syms, manin_symbols.ManinSymbolList): - raise TypeError, "syms must be a ManinSymbolList" + raise TypeError("syms must be a ManinSymbolList") tm = misc.verbose() # We will fill in this set with the relations x_i + s*x_j = 0, # where the notation is as in _sparse_2term_quotient. @@ -517,10 +517,10 @@ def sparse_2term_quotient(rels, n, F): [(3, -1/3), (3, -1), (3, -1), (3, 1), (5, 1), (5, 1)] """ if not isinstance(rels, set): - raise TypeError, "rels must be a set" + raise TypeError("rels must be a set") n = int(n) if not isinstance(F, rings.Ring): - raise TypeError, "F must be a ring." + raise TypeError("F must be a ring.") tm = misc.verbose("Starting sparse 2-term quotient...") free = range(n) diff --git a/src/sage/modular/modsym/space.py b/src/sage/modular/modsym/space.py index e96675b1dc1..473d613ef32 100644 --- a/src/sage/modular/modsym/space.py +++ b/src/sage/modular/modsym/space.py @@ -196,7 +196,7 @@ def compact_system_of_eigenvalues(self, v, names='alpha', nz=None): E = M.hecke_images(nz, v) * self.dual_free_module().basis_matrix().transpose() except AttributeError: # TODO!!! - raise NotImplementedError, "ambient space must implement hecke_images but doesn't yet" + raise NotImplementedError("ambient space must implement hecke_images but doesn't yet") v = self.dual_eigenvector(names=names, lift=False, nz=nz) return E, v @@ -230,7 +230,7 @@ def cuspidal_submodule(self): sage: ModularSymbols(Gamma0(11),2).cuspidal_submodule() Modular Symbols subspace of dimension 2 of Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field """ - raise NotImplementedError, "computation of cuspidal submodule not yet implemented for this class" + raise NotImplementedError("computation of cuspidal submodule not yet implemented for this class") def cuspidal_subspace(self): """ @@ -309,7 +309,7 @@ def dimension_of_associated_cuspform_space(self): 32 """ if not self.is_cuspidal(): - raise ArithmeticError, "space must be cuspidal" + raise ArithmeticError("space must be cuspidal") if self.sign() == 0: return self.dimension() // 2 return self.dimension() @@ -334,7 +334,7 @@ def dual_star_involution_matrix(self): [ 0 -1 0] [ 0 1 1] """ - raise NotImplementedError, "computation of dual star involution matrix not yet implemented for this class" + raise NotImplementedError("computation of dual star involution matrix not yet implemented for this class") def group(self): """ @@ -393,7 +393,7 @@ def is_cuspidal(self): sage: ModularSymbols(Gamma0(11),2).is_cuspidal() False """ - raise NotImplementedError, "computation of cuspidal subspace not yet implemented for this class" + raise NotImplementedError("computation of cuspidal subspace not yet implemented for this class") def is_simple(self): """ @@ -449,7 +449,7 @@ def multiplicity(self, S, check_simple=True): if self.level() % S.level() != 0 or S.weight() != self.weight(): return 0 if check_simple and not S.is_simple(): - raise ArithmeticError, "S must be simple" + raise ArithmeticError("S must be simple") A = self.ambient_hecke_module() B = A.submodule_generated_by_images(S) C = self.intersection(B) @@ -678,10 +678,10 @@ def q_expansion_basis(self, prec=None, algorithm='default'): prec = Integer(prec) if prec < 1: - raise ValueError, "prec (=%s) must be >= 1"%prec + raise ValueError("prec (=%s) must be >= 1"%prec) if not self.is_cuspidal(): - raise ArithmeticError, "space must be cuspidal" + raise ArithmeticError("space must be cuspidal") if self.sign() == 0: P = self.plus_submodule(compute_dual=True) @@ -700,10 +700,10 @@ def q_expansion_basis(self, prec=None, algorithm='default'): B1 = self._q_expansion_basis_hecke_dual(prec) B2 = self._q_expansion_basis_eigen(prec, 'alpha') if B1 != B2: - raise RuntimeError, "There is a bug in q_expansion_basis -- basis computed differently with two algorithms:\n%s\n%s\n"%(B1, B2,) + raise RuntimeError("There is a bug in q_expansion_basis -- basis computed differently with two algorithms:\n%s\n%s\n"%(B1, B2,)) return Sequence(B1, cr=True) else: - raise ValueError, "no algorithm '%s'"%algorithm + raise ValueError("no algorithm '%s'"%algorithm) def q_expansion_module(self, prec = None, R=None): r""" @@ -884,7 +884,7 @@ def q_expansion_module(self, prec = None, R=None): ## names is never used in this case return self._q_expansion_module(prec) else: - raise NotImplementedError, "R must be ZZ, QQ, or the base ring of the modular symbols space." + raise NotImplementedError("R must be ZZ, QQ, or the base ring of the modular symbols space.") def _q_eigenform_images(self, A, prec, names): """ @@ -937,19 +937,19 @@ def _q_expansion_module(self, prec, algorithm='hecke'): """ if not self.is_cuspidal(): - raise ValueError, "self must be cuspidal" + raise ValueError("self must be cuspidal") R = self.base_ring() if not R.is_field(): if R == ZZ: return self._q_expansion_module_integral(prec) - raise NotImplementedError, "base ring must be a field (or ZZ)." + raise NotImplementedError("base ring must be a field (or ZZ).") if algorithm == 'hecke' or algorithm == 'default': A = R ** prec return A.span([f.padded_list(prec) for f in self.q_expansion_basis(prec, algorithm)]) if algorithm != 'eigen': - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) V = R ** prec def q_eigen_gens(f): @@ -1003,10 +1003,10 @@ def _q_expansion_module_rational(self, prec): [ 0 0 1 -4 2] """ if not self.is_cuspidal(): - raise ValueError, "self must be cuspidal" + raise ValueError("self must be cuspidal") K = self.base_ring() if not is_NumberField(K): - raise TypeError, "self must be over QQ or a number field." + raise TypeError("self must be over QQ or a number field.") n = K.degree() if n == 1: return self._q_expansion_module(prec) @@ -1098,9 +1098,9 @@ def congruence_number(self, other, prec=None): 2 """ if not self.is_cuspidal(): - raise ValueError, "self must be cuspidal" + raise ValueError("self must be cuspidal") if not other.is_cuspidal(): - raise ValueError, "right must be cuspidal" + raise ValueError("right must be cuspidal") if prec is None: prec = max(self.hecke_bound(), other.hecke_bound()) prec = int(prec) @@ -1203,7 +1203,7 @@ def q_eigenform(self, prec, names=None): ArithmeticError: self must be cuspidal. """ if self.dimension() > 1 and names is None: - raise ValueError, "please specify a name to use for the field of eigenvalues" + raise ValueError("please specify a name to use for the field of eigenvalues") if prec is None: prec = self.default_prec() @@ -1212,12 +1212,12 @@ def q_eigenform(self, prec, names=None): except (AttributeError, KeyError): self._q_expansion_dict = {} if not self.is_cuspidal(): - raise ArithmeticError, "self must be cuspidal." + raise ArithmeticError("self must be cuspidal.") if not self.is_simple(): if self.sign() == 0: return self.plus_submodule(compute_dual=True).q_eigenform(prec, names) - raise ArithmeticError, "self must be simple." + raise ArithmeticError("self must be simple.") a2 = self.eigenvalue(2, names) R = PowerSeriesRing(a2.parent(), "q") q = R.gen(0) @@ -1312,7 +1312,7 @@ def q_expansion_cuspforms(self, prec=None): if prec is None: prec = self.default_prec() if not self.is_cuspidal(): - raise ArithmeticError, "self must be cuspidal" + raise ArithmeticError("self must be cuspidal") K = self.base_ring() M = matrix_space.MatrixSpace(K, prec-1, self.dimension()) T = [self.dual_hecke_matrix(n) for n in range(1,prec)] @@ -1336,7 +1336,7 @@ def _q_expansion_basis_hecke_dual(self, prec): d = self.dimension_of_associated_cuspform_space() prec = Integer(prec) if prec < 1: - raise ValueError, "prec (=%s) must be >= 1"%prec + raise ValueError("prec (=%s) must be >= 1"%prec) if d >= prec-1: d = prec-1 K = self.base_ring() @@ -1580,9 +1580,9 @@ def intersection_number(self, M): 400 """ if not isinstance(M, ModularSymbolsSpace): - raise TypeError, "M must be a modular symbols space" + raise TypeError("M must be a modular symbols space") if M.ambient() != self.ambient(): - raise ValueError, "self and M must be in the same ambient space." + raise ValueError("self and M must be in the same ambient space.") A = self.integral_structure() B = M.integral_structure() return (A+B).index_in_saturation() @@ -1821,7 +1821,7 @@ def _set_sign(self, sign): """ sign = int(sign) if not (sign in [-1,0,1]): - raise ValueError, "sign (=%s) must be -1, 0, or 1"%sign + raise ValueError("sign (=%s) must be -1, 0, or 1"%sign) self.__sign = sign def sign_submodule(self, sign, compute_dual=True): @@ -1852,7 +1852,7 @@ def sign_submodule(self, sign, compute_dual=True): """ sign = int(sign) if not sign in [-1, 0, 1]: - raise ValueError, "sign must be -1, 0 or 1" + raise ValueError("sign must be -1, 0 or 1") if self.sign() == sign: # an easy case return self if self.sign() == -sign: # another easy case @@ -1860,7 +1860,7 @@ def sign_submodule(self, sign, compute_dual=True): if sign == 0: # if sign is zero then self.sign() isn't 0 because # of the above checks. - raise ArithmeticError, "There is no sign 0 subspace of a space of modular symbols with nonzero sign." + raise ArithmeticError("There is no sign 0 subspace of a space of modular symbols with nonzero sign.") try: return self.__plus_submodule[(sign, compute_dual)] except AttributeError: @@ -1924,7 +1924,7 @@ def abelian_variety(self): return self.__modular_abelian_variety except AttributeError: if not self.is_cuspidal(): - raise ValueError, "self must be cuspidal" + raise ValueError("self must be cuspidal") from sage.modular.abvar.abvar import ModularAbelianVariety_modsym A = ModularAbelianVariety_modsym(self, check=False) self.__modular_abelian_variety = A @@ -2033,9 +2033,9 @@ def integral_period_mapping(self): except AttributeError: pass if self.base_ring() != QQ: - raise ValueError, "integral mapping only defined for spaces over QQ" + raise ValueError("integral mapping only defined for spaces over QQ") if not self.is_cuspidal(): - raise ValueError, "integral mapping only defined for cuspidal spaces" + raise ValueError("integral mapping only defined for cuspidal spaces") D = self.dual_free_module().basis_matrix().transpose() I = self.ambient_module().cuspidal_submodule().integral_structure().basis_matrix() # image of cuspidal integral submodule @@ -2109,7 +2109,7 @@ def modular_symbols_of_sign(self, sign, bound=None): if sign == self.sign(): return self if not self.is_cuspidal(): - raise ValueError, "self must be cuspidal for modular symbols space with given sign to be defined." + raise ValueError("self must be cuspidal for modular symbols space with given sign to be defined.") d = self.dimension() if d == 0: return self @@ -2164,9 +2164,9 @@ def abvarquo_cuspidal_subgroup(self): try: return self.__abvarquo_cuspidal_subgroup except AttributeError: pass if self.base_ring() != QQ: - raise ValueError, "base ring must be QQ" + raise ValueError("base ring must be QQ") if self.weight() != 2: - raise NotImplementedError, "only implemented when weight is 2" + raise NotImplementedError("only implemented when weight is 2") M = self.ambient_module() phi = self.integral_period_mapping() @@ -2251,12 +2251,12 @@ def abvarquo_rational_cuspidal_subgroup(self): try: return self.__abvarquo_rational_cuspidal_subgroup except AttributeError: pass if self.base_ring() != QQ: - raise ValueError, "base ring must be QQ" + raise ValueError("base ring must be QQ") if self.weight() != 2: - raise NotImplementedError, "only implemented when weight is 2" + raise NotImplementedError("only implemented when weight is 2") if not is_Gamma0(self.group()): # todo -- do Gamma1 and GammaH, which are easy - raise NotImplementedError, "only implemented when group is Gamma0" + raise NotImplementedError("only implemented when group is Gamma0") N = self.level() if N.is_squarefree(): return self.abvarquo_cuspidal_subgroup() diff --git a/src/sage/modular/modsym/subspace.py b/src/sage/modular/modsym/subspace.py index 9d2f31f541f..88e89ad6736 100644 --- a/src/sage/modular/modsym/subspace.py +++ b/src/sage/modular/modsym/subspace.py @@ -307,8 +307,8 @@ def factorization(self): r = self.dimension() s = sum([A.rank()*mult for A, mult in D]) if r != s: - raise NotImplementedError, "modular symbols factorization not fully implemented yet -- self has dimension %s, but sum of dimensions of factors is %s"%( - r, s) + raise NotImplementedError("modular symbols factorization not fully implemented yet -- self has dimension %s, but sum of dimensions of factors is %s"%( + r, s)) self._factorization = sage.structure.factorization.Factorization(D, cr=True) return self._factorization diff --git a/src/sage/modular/modsym/tests.py b/src/sage/modular/modsym/tests.py index 1ec301cce19..31b22172ff9 100644 --- a/src/sage/modular/modsym/tests.py +++ b/src/sage/modular/modsym/tests.py @@ -63,9 +63,9 @@ def __init__(self, levels=20, weights=4, onlyg0=False, onlyg1=False, onlychar=Fa self.levels = levels self.weights = weights if len(levels) < 1: - raise RuntimeError, "levels must have positive length" + raise RuntimeError("levels must have positive length") if len(weights) < 1: - raise RuntimeError, "weights must have positive length" + raise RuntimeError("weights must have positive length") self.current_space = None self.onlyg0 = onlyg0 self.onlyg1 = onlyg1 diff --git a/src/sage/modular/overconvergent/genus0.py b/src/sage/modular/overconvergent/genus0.py index 6c1cc1286ac..8e112b21a43 100644 --- a/src/sage/modular/overconvergent/genus0.py +++ b/src/sage/modular/overconvergent/genus0.py @@ -244,7 +244,7 @@ def OverconvergentModularForms(prime, weight, radius, base_ring=QQ, prec = 20, c if char is None: char = trivial_character(prime, base_ring=QQ) if int(prime) not in [2, 3, 5, 7, 13]: - raise ValueError, "p must be one of {2, 3, 5, 7, 13}" + raise ValueError("p must be one of {2, 3, 5, 7, 13}") key = (prime, weight, radius, base_ring, prec, char) if key in __ocmfdict: w = __ocmfdict[key] @@ -297,10 +297,10 @@ def __init__(self, prime, weight, radius, base_ring, prec, char): self._p = prime if not ( base_ring == QQ or is_pAdicField(base_ring) ): - raise TypeError, "Base ring must be QQ or a p-adic field" + raise TypeError("Base ring must be QQ or a p-adic field") if base_ring != QQ and base_ring.prime() != self._p: - raise TypeError, "Residue characteristic of base ring (=%s) must be %s" % (base_ring, self._p) + raise TypeError("Residue characteristic of base ring (=%s) must be %s" % (base_ring, self._p)) if isinstance(weight, WeightCharacter): self._wtchar = weight @@ -308,7 +308,7 @@ def __init__(self, prime, weight, radius, base_ring, prec, char): self._wtchar = WeightSpace(prime, base_ring = char.base_ring())(weight, char, algebraic=True) if not self._wtchar.is_even(): - raise ValueError, "Weight-character must be even" + raise ValueError("Weight-character must be even") Module_old.__init__(self, base_ring) @@ -359,7 +359,7 @@ def _set_radius(self, radius): p = ZZ(self.prime()) if (radius < 0 or radius > p/(p+1)): - raise ValueError, "radius (=%s) must be between 0 and p/(p+1)" % radius + raise ValueError("radius (=%s) must be between 0 and p/(p+1)" % radius) d = 12/(p-1)*radius if d.is_integral(): self._const = p ** ZZ(d) @@ -372,7 +372,7 @@ def _set_radius(self, radius): pi = p e = d if not e.is_integral(): - raise ValueError, "no element of base ring (=%s) has normalised valuation %s" % (self.base_ring(), radius * 12 /(p-1)) + raise ValueError("no element of base ring (=%s) has normalised valuation %s" % (self.base_ring(), radius * 12 /(p-1))) self._radius = radius self._const = pi ** ZZ(e) @@ -424,7 +424,7 @@ def base_extend(self, ring): if ring.has_coerce_map_from(self.base_ring()): return self.change_ring(ring) else: - raise TypeError, "Base extension of self (over '%s') to ring '%s' not defined." % (self.base_ring(), ring) + raise TypeError("Base extension of self (over '%s') to ring '%s' not defined." % (self.base_ring(), ring)) def _an_element_impl(self): r""" @@ -707,11 +707,11 @@ def __call__(self, input): p = ZZ(self.prime()) nu = (input.level() == 1 and p/(p+1)) or (1 / (p + 1) * p**(2 - input.level().valuation(p))) if self.radius() > nu: - raise ValueError, "Form is not overconvergent enough (form is only %s-overconvergent)" % nu + raise ValueError("Form is not overconvergent enough (form is only %s-overconvergent)" % nu) else: return self(self._qsr(input.q_expansion(self.prec()))) else: - raise TypeError, "Cannot create an element of '%s' from element of incompatible space '%s'" % (self, input.parent()) + raise TypeError("Cannot create an element of '%s' from element of incompatible space '%s'" % (self, input.parent())) elif isinstance(input, (list, tuple, Vector)): v = list(input) @@ -722,7 +722,7 @@ def __call__(self, input): return OverconvergentModularFormElement(self, gexp=None, qexp=self._qsr(input)) else: - raise TypeError, "Don't know how to create an overconvergent modular form from %s" % input + raise TypeError("Don't know how to create an overconvergent modular form from %s" % input) @cached_method def zero_element(self): @@ -754,7 +754,7 @@ def _coerce_from_ocmf(self, f): """ prime, weight, radius, base_ring, prec, char = f.parent()._params() if (prime, weight, char) != (self.prime(), self.weight().k(), self.weight().chi()): - raise TypeError, "Cannot create an element of '%s' from element of incompatible space '%s'" % (self, input.parent()) + raise TypeError("Cannot create an element of '%s' from element of incompatible space '%s'" % (self, input.parent())) return self(self._qsr(f.q_expansion())) def _coerce_impl(self, x): @@ -838,7 +838,7 @@ def gens_dict(self): TypeError: gens_dict does not make sense as number of generators is infinite """ - raise TypeError, "gens_dict does not make sense as number of generators is infinite" + raise TypeError("gens_dict does not make sense as number of generators is infinite") ##################################### # Routines with some actual content # @@ -873,7 +873,7 @@ def hecke_operator(self, f, m): if f.parent() is self.base_extend(f.parent().base_ring()): return f.parent().hecke_operator(f, m) else: - raise TypeError, "Not an element of this space" + raise TypeError("Not an element of this space") else: return hecke_operator_on_qexp(f, m, self.weight().k(), eps=self.weight().chi()) @@ -945,23 +945,23 @@ def hecke_matrix(self, m, n, use_recurrence = False, exact_arith = False): mat[i,j] = l[i] except IndexError: if not self.weight().is_zero(): - raise ValueError, "n is too large for current precision" + raise ValueError("n is too large for current precision") else: if i <= self.prime() * j: - raise ValueError, "n is too large computing initial conds: can't work out u[%s, %s]" % (i,j) + raise ValueError("n is too large computing initial conds: can't work out u[%s, %s]" % (i,j)) else: mat[i,j] = 0 # computations are exact for weight 0, and we know these terms are zero if use_recurrence: - if m != self.prime(): raise ValueError, "Recurrence method not valid when m != p" + if m != self.prime(): raise ValueError("Recurrence method not valid when m != p") for j in xrange(self.prime(), n): # can only apply recurrence if have i,j both >= p. if j >= self.prec(): for i in xrange(self.prime()): if self.weight() != 0: - raise ValueError, "n is too large for current precision" + raise ValueError("n is too large for current precision") else: if j <= self.prime() * i: - raise ValueError, "n is too large computing initial conds: can't work out u[%s,%s]" % (i,j) + raise ValueError("n is too large computing initial conds: can't work out u[%s,%s]" % (i,j)) mat[i,j] = 0 @@ -976,7 +976,7 @@ def hecke_matrix(self, m, n, use_recurrence = False, exact_arith = False): else: if( n*self.prime() > self.prec()): - raise ValueError, "n is too large" + raise ValueError("n is too large") for j in xrange(self.prime(), n): l = self._convert_to_basis(self.hecke_operator(self._basis_cache[j], m)) for i in xrange(n): @@ -1099,7 +1099,7 @@ def eigenfunctions(self, n, F = None, exact_arith=True): # we're in the 0 component of weight-character space. But normalising the const term # to 1 works as *none of the small primes we deal with are irregular*! :-) else: - raise ValueError, "Constant and linear terms both zero!" + raise ValueError("Constant and linear terms both zero!") # if this gets called something is very wrong. efunc = OverconvergentModularFormElement(self.base_extend(F), gexp=gexp) @@ -1184,7 +1184,7 @@ def _discover_recurrence_matrix(self, use_smithline=True): coeffs = [] for i in xrange(self.prime()+2): if not h.valuation() >= i: - raise ValueError, "Something strange is happening here" + raise ValueError("Something strange is happening here") coeffs.append(h[i] / fi[i]) h = h - coeffs[-1] * fi @@ -1267,7 +1267,7 @@ def __init__(self, parent, gexp=None, qexp=None): self._p = self.parent().prime() #self.weight = self.parent().weight if (gexp is None and qexp is None) or (gexp is not None and qexp is not None): - raise ValueError, "Must supply exactly one of a q-expansion and a g-expansion" + raise ValueError("Must supply exactly one of a q-expansion and a g-expansion") if gexp is not None: self._gexp = gexp.add_bigoh(self.parent().prec()) self._qexp = sum([self.parent()._basis_cache[i] * gexp[i] for i in xrange(min(gexp.prec(), self.parent().prec()))]) @@ -1369,7 +1369,7 @@ def slope(self): ... TypeError: slope only defined for eigenfunctions """ - if not self.is_eigenform(): raise TypeError, "slope only defined for eigenfunctions" + if not self.is_eigenform(): raise TypeError("slope only defined for eigenfunctions") return self._slope def eigenvalue(self): @@ -1390,7 +1390,7 @@ def eigenvalue(self): TypeError: eigenvalue only defined for eigenfunctions """ - if not self.is_eigenform(): raise TypeError, "eigenvalue only defined for eigenfunctions" + if not self.is_eigenform(): raise TypeError("eigenvalue only defined for eigenfunctions") return self._eigenvalue def q_expansion(self, prec=None): @@ -1445,7 +1445,7 @@ def coordinates(self, prec=None): """ - if prec > self.prec(): raise ValueError, "Precision too large for space" + if prec > self.prec(): raise ValueError("Precision too large for space") if prec is None: prec = self.prec() return self._gexp.padded_list(prec) @@ -1520,7 +1520,7 @@ def __cmp__(self, other): """ if other.parent() != self.parent(): - raise ArithmeticError, "Can't get here!" + raise ArithmeticError("Can't get here!") return cmp(self.gexp(), other.gexp()) def r_ord(self, r): @@ -1589,7 +1589,7 @@ def governing_term(self, r): for i in xrange(self.gexp().prec()): if 12/ZZ(p - 1)*i*(r - s) - F(self.gexp()[i]).normalized_valuation() == self.r_ord(r): return i - raise RuntimeError, "Can't get here" + raise RuntimeError("Can't get here") def valuation_plot(self, rmax = None): r""" diff --git a/src/sage/modular/overconvergent/hecke_series.py b/src/sage/modular/overconvergent/hecke_series.py index 232d62e26da..725b35a2e97 100644 --- a/src/sage/modular/overconvergent/hecke_series.py +++ b/src/sage/modular/overconvergent/hecke_series.py @@ -1048,11 +1048,11 @@ def is_valid_weight_list(klist,p): ValueError: List of weights must be all congruent modulo p-1 = 4, but given list contains -3 and 2 which are not congruent """ if len(klist) == 0: - raise ValueError, "List of weights must be non-empty" + raise ValueError("List of weights must be non-empty") k0 = klist[0] % (p-1) for i in xrange(1,len(klist)): if (klist[i] % (p-1)) != k0: - raise ValueError, "List of weights must be all congruent modulo p-1 = %s, but given list contains %s and %s which are not congruent" % (p-1, klist[0], klist[i]) + raise ValueError("List of weights must be all congruent modulo p-1 = %s, but given list contains %s and %s which are not congruent" % (p-1, klist[0], klist[i])) def hecke_series(p,N,klist,m, modformsring = False, weightbound = 6): r""" @@ -1130,11 +1130,11 @@ def hecke_series(p,N,klist,m, modformsring = False, weightbound = 6): # algorithm may finish with false output unless: is_valid_weight_list(klist,p) if not p.is_prime(): - raise ValueError, "p (=%s) is not prime" % p + raise ValueError("p (=%s) is not prime" % p) if p < 5: - raise ValueError, "p = 2 and p = 3 not supported" + raise ValueError("p = 2 and p = 3 not supported") if not N%p: - raise ValueError, "Level (=%s) should be prime to p (=%s)" % (N, p) + raise ValueError("Level (=%s) should be prime to p (=%s)" % (N, p)) # return all 1 list for odd weights if klist[0] % 2 == 1: diff --git a/src/sage/modular/overconvergent/weightspace.py b/src/sage/modular/overconvergent/weightspace.py index 95f257abde8..04a15764635 100644 --- a/src/sage/modular/overconvergent/weightspace.py +++ b/src/sage/modular/overconvergent/weightspace.py @@ -132,7 +132,7 @@ def __init__(self, p, base_ring): ParentWithBase.__init__(self, base=base_ring) p = ZZ(p) if not p.is_prime(): - raise ValueError, "p must be prime" + raise ValueError("p must be prime") self._p = p self._param = Qp(p)((p == 2 and 5) or (p + 1)) @@ -191,7 +191,7 @@ def __call__(self, arg1, arg2 = None, algebraic=True): elif arg1.parent().prime() == self.prime(): return self._coerce_in_wtchar(arg1) else: - raise TypeError, "Incompatible type!" + raise TypeError("Incompatible type!") if algebraic: return AlgebraicWeight(self, arg1, arg2) @@ -240,7 +240,7 @@ def base_extend(self, R): if R.has_coerce_map_from(self.base_ring()): return WeightSpace_constructor(self.prime(), R) else: - raise TypeError, "No coercion map from '%s' to '%s' is defined" % (self.base_ring(), R) + raise TypeError("No coercion map from '%s' to '%s' is defined" % (self.base_ring(), R)) def _coerce_impl(self, x): r""" @@ -346,7 +346,7 @@ def pAdicEisensteinSeries(self, ring, prec=20): 1 - 9*q + 27*q^2 - 9*q^3 - 117*q^4 + 216*q^5 + 27*q^6 - 450*q^7 + 459*q^8 - 9*q^9 - 648*q^10 + 1080*q^11 - 117*q^12 - 1530*q^13 + 1350*q^14 + 216*q^15 - 1845*q^16 + 2592*q^17 + 27*q^18 - 3258*q^19 + O(q^20) """ if not self.is_even(): - raise ValueError, "Eisenstein series not defined for odd weight-characters" + raise ValueError("Eisenstein series not defined for odd weight-characters") q = ring.gen() s = ring(1) + 2*self.one_over_Lvalue() * sum([sum([self(d)/d for d in divisors(n)]) * q**n for n in xrange(1, prec)]) return s.add_bigoh(prec) @@ -487,7 +487,7 @@ def __init__(self, parent, k, chi=None): if n == 1: n = self._p if not n.is_power_of(self._p): - raise ValueError, "Character must have %s-power conductor" % p + raise ValueError("Character must have %s-power conductor" % p) self._chi = DirichletGroup(n, chi.base_ring())(chi) def __call__(self, x): @@ -528,7 +528,7 @@ def __call__(self, x): """ if isinstance(x, pAdicGenericElement): if x.parent().prime() != self._p: - raise TypeError, "x must be an integer or a %s-adic integer" % self._p + raise TypeError("x must be an integer or a %s-adic integer" % self._p) if self._p**(x.precision_absolute()) < self._chi.conductor(): raise PrecisionError("Precision too low") xint = x.lift() @@ -643,7 +643,7 @@ def Lvalue(self): if self.is_trivial(): return Infinity else: - raise NotImplementedError, "Don't know how to compute value of this L-function" + raise NotImplementedError("Don't know how to compute value of this L-function") class ArbitraryWeight(WeightCharacter): @@ -663,7 +663,7 @@ def __init__(self, parent, w, t): self.t = ZZ(t) % (self._p > 2 and (self._p - 1) or 2) # do we store w precisely? if (w - 1).valuation() <= 0: - raise ValueError, "Must send generator to something nearer 1" + raise ValueError("Must send generator to something nearer 1") self.w = w def _repr_(self): diff --git a/src/sage/modular/quatalg/brandt.py b/src/sage/modular/quatalg/brandt.py index 9a826438c2d..1c47fc24b15 100644 --- a/src/sage/modular/quatalg/brandt.py +++ b/src/sage/modular/quatalg/brandt.py @@ -298,21 +298,21 @@ def BrandtModule(N, M=1, weight=2, base_ring=QQ, use_cache=True): """ N, M, weight = Integer(N), Integer(M), Integer(weight) if not N.is_prime(): - raise NotImplementedError, "Brandt modules currently only implemented when N is a prime" + raise NotImplementedError("Brandt modules currently only implemented when N is a prime") if M < 1: - raise ValueError, "M must be positive" + raise ValueError("M must be positive") if gcd(M,N) != 1: - raise ValueError, "M must be coprime to N" + raise ValueError("M must be coprime to N") if weight < 2: - raise ValueError, "weight must be at least 2" + raise ValueError("weight must be at least 2") if not is_CommutativeRing(base_ring): - raise TypeError, "base_ring must be a commutative ring" + raise TypeError("base_ring must be a commutative ring") key = (N, M, weight, base_ring) if use_cache: if key in cache: # TODO: re-enable caching! return cache[key] if weight != 2: - raise NotImplementedError, "weight != 2 not yet implemented" + raise NotImplementedError("weight != 2 not yet implemented") B = BrandtModule_class(*key) if use_cache: cache[key] = B @@ -478,7 +478,7 @@ def __init__(self, N, M, weight, base_ring): self.__N = N self.__M = M if not N.is_prime(): - raise NotImplementedError, "right now N must be prime" + raise NotImplementedError("right now N must be prime") rank = class_number(N, 1, M) self.__key = (N, M, weight, base_ring) AmbientHeckeModule.__init__(self, base_ring, rank, N * M, weight=2) @@ -678,9 +678,9 @@ def cyclic_submodules(self, I, p): ValueError: p must be coprime to the level """ if not Integer(p).is_prime(): - raise ValueError, "p must be a prime" + raise ValueError("p must be a prime") if self.level() % p == 0: - raise ValueError, "p must be coprime to the level" + raise ValueError("p must be coprime to the level") R = self.order_of_level_N() A = R.quaternion_algebra() @@ -829,7 +829,7 @@ def hecke_matrix(self, n, algorithm='default', sparse=False, B=None): """ n = ZZ(n) if n <= 0: - raise IndexError, "n must be positive." + raise IndexError("n must be positive.") if n not in self._hecke_matrices: if algorithm == 'default': try: pr = len(self.__brandt_series_vectors[0][0]) @@ -848,7 +848,7 @@ def hecke_matrix(self, n, algorithm='default', sparse=False, B=None): elif algorithm == 'brandt': T = self._compute_hecke_matrix_brandt(n, sparse=sparse) else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) T.set_immutable() self._hecke_matrices[n] = T return self._hecke_matrices[n] @@ -938,7 +938,7 @@ def _compute_hecke_matrix_directly(self, n, B=None, sparse=False): """ level = self.level() if gcd(n, level) != 1: - raise ValueError, "n must be coprime to the level" + raise ValueError("n must be coprime to the level") # For rigor it does not matter at all what bound we chose. # This B is used only for the first phase of checking equality @@ -1233,7 +1233,7 @@ def _brandt_series_vectors(self, prec=None): except AttributeError: prec = 2 elif prec < 2: - raise ValueError, "prec must be at least 2" + raise ValueError("prec must be at least 2") L = self.right_ideals() n = len(L) K = QQ @@ -1325,7 +1325,7 @@ def eisenstein_subspace(self): try: return self.__eisenstein_subspace except AttributeError: pass if self.base_ring().characteristic() != 0: - raise ValueError, "characteristic must be 0" + raise ValueError("characteristic must be 0") # cut down until we get a 1-d space using Hecke operators T_p # with p coprime to the level. V = self @@ -1412,12 +1412,12 @@ def quaternion_order_with_given_level(A, level): """ if not is_RationalField(A.base_ring()): - raise NotImplementedError, "base field must be rational numbers" + raise NotImplementedError("base field must be rational numbers") from sage.modular.quatalg.brandt import maximal_order if len(A.ramified_primes()) > 1: - raise NotImplementedError, "Currently this algorithm only works when the quaternion algebra is only ramified at one finite prime." + raise NotImplementedError("Currently this algorithm only works when the quaternion algebra is only ramified at one finite prime.") # (The algorithm we use is similar to that in Magma (by David Kohel).) # in the following magma code, M denotes is the level @@ -1430,7 +1430,7 @@ def quaternion_order_with_given_level(A, level): if 0 and N1 != 1: # we don't know why magma does the following, so we don't do it. for p in A.ramified_primes(): if level % p**2 == 0: - raise NotImplementedError, "Currently sage can only compute orders whose level is divisible by at most one power of any prime that ramifies in the quaternion algebra" + raise NotImplementedError("Currently sage can only compute orders whose level is divisible by at most one power of any prime that ramifies in the quaternion algebra") P = basis_for_left_ideal(O, [N1] + [x*y - y*x for x, y in cartesian_product_iterator([A.basis(), A.basis()]) ]) O = A.quaternion_order(P) diff --git a/src/sage/modular/ssmod/ssmod.py b/src/sage/modular/ssmod/ssmod.py index da59302c565..f389a4acc48 100644 --- a/src/sage/modular/ssmod/ssmod.py +++ b/src/sage/modular/ssmod/ssmod.py @@ -193,7 +193,7 @@ def Phi_polys(L, x, j): - Iftikhar Burhanuddin -- burhanud@usc.edu """ if not(L in [2,3,5,7,11]): - raise ValueError, "L should be either 2,3,5,7 or 11. For other values use ClassicalModularPolynomialDatabase()." + raise ValueError("L should be either 2,3,5,7 or 11. For other values use ClassicalModularPolynomialDatabase().") j_tmp = 1 j_pow = [j_tmp] @@ -486,7 +486,7 @@ def dimension_supersingular_module(prime, level=1): - Iftikhar Burhanuddin - burhanud@usc.edu """ if not(rings.Integer(prime).is_prime()): - raise ValueError, "%s is not a prime"%prime + raise ValueError("%s is not a prime"%prime) if level == 1: return Gamma0(prime).dimension_modular_forms(2) @@ -534,7 +534,7 @@ def supersingular_D(prime): - Iftikhar Burhanuddin - burhanud@usc.edu """ if not(rings.Integer(prime).is_prime()): - raise ValueError, "%s is not a prime"%prime + raise ValueError("%s is not a prime"%prime) #Making picking D more intelligent D = -1 @@ -581,12 +581,12 @@ def supersingular_j(FF): - Iftikhar Burhanuddin -- burhanud@usc.edu """ if not(FF.is_field()) or not(FF.is_finite()): - raise ValueError, "%s is not a finite field"%FF + raise ValueError("%s is not a finite field"%FF) prime = FF.characteristic() if not(rings.Integer(prime).is_prime()): - raise ValueError, "%s is not a prime"%prime + raise ValueError("%s is not a prime"%prime) if not(rings.Integer(FF.cardinality())) == rings.Integer(prime**2): - raise ValueError, "%s is not a quadratic extension"%FF + raise ValueError("%s is not a quadratic extension"%FF) if rings.kronecker(-1, prime) != 1: j_invss = 1728 #(2^2 * 3)^3 elif rings.kronecker(-2, prime) != 1: @@ -652,11 +652,11 @@ def __init__(self, prime=2, level=1, base_ring=rings.IntegerRing()): """ if not prime.is_prime(): - raise ValueError, "the argument prime must be a prime number" + raise ValueError("the argument prime must be a prime number") if prime.divides(level): - raise ValueError, "the argument level must be coprime to the argument prime" + raise ValueError("the argument level must be coprime to the argument prime") if level != 1: - raise NotImplementedError, "supersingular modules of level > 1 not yet implemented" + raise NotImplementedError("supersingular modules of level > 1 not yet implemented") self.__prime = prime from sage.rings.all import FiniteField self.__finite_field = FiniteField(prime**2,'a') diff --git a/src/sage/modules/fg_pid/fgp_module.py b/src/sage/modules/fg_pid/fgp_module.py index ee464a5ec16..f3208aa85b3 100644 --- a/src/sage/modules/fg_pid/fgp_module.py +++ b/src/sage/modules/fg_pid/fgp_module.py @@ -340,13 +340,13 @@ def __init__(self, V, W, check=True): """ if check: if not is_FreeModule(V): - raise TypeError, "V must be a FreeModule" + raise TypeError("V must be a FreeModule") if not is_FreeModule(W): - raise TypeError, "W must be a FreeModule" + raise TypeError("W must be a FreeModule") if not W.is_submodule(V): - raise ValueError, "W must be a submodule of V" + raise ValueError("W must be a submodule of V") if V.base_ring() != W.base_ring(): - raise ValueError, "W and V must have the same base ring" + raise ValueError("W and V must have the same base ring") self._W = W self._V = V Module.__init__(self, base=V.base_ring()) @@ -458,9 +458,9 @@ def __div__(self, other): if is_FreeModule(other): other = other / other.zero_submodule() else: - raise TypeError, "other must be an FGP module" + raise TypeError("other must be an FGP module") if not other.is_submodule(self): - raise ValueError, "other must be a submodule of self" + raise ValueError("other must be a submodule of self") return self._module_constructor(self._V, other._V+self._W) def __eq__(self, other): @@ -615,7 +615,7 @@ def _element_constructor_(self, x, check=True): try: x = self.optimized()[0].V().linear_combination_of_basis(x) except ValueError as msg: - raise TypeError, msg + raise TypeError(msg) elif isinstance(x, FGP_Element): x = x.lift() return self.element_class(self, self._V(x)) @@ -636,7 +636,7 @@ def linear_combination_of_smith_form_gens(self, x): try: x = self.optimized()[0].V().linear_combination_of_basis(x) except ValueError as msg: - raise TypeError, msg + raise TypeError(msg) return self.element_class(self, self._V(x)) def __contains__(self, x): @@ -708,16 +708,16 @@ def submodule(self, x): """ if is_FGP_Module(x): if not x._W.is_submodule(self._W): - raise ValueError, "x.W() must be contained in self's W." + raise ValueError("x.W() must be contained in self's W.") V = x._V if not V.is_submodule(self._V): - raise ValueError, "x.V() must be contained in self's V." + raise ValueError("x.V() must be contained in self's V.") return x if not isinstance(x, (list, tuple)): - raise TypeError, "x must be a list, tuple, or FGP module" + raise TypeError("x must be a list, tuple, or FGP module") x = Sequence(x) if is_FGP_Module(x.universe()): @@ -1128,7 +1128,7 @@ def gen(self, i): """ v = self.gens() if i < 0 or i >= len(v): - raise ValueError, "Generator %s not defined"%i + raise ValueError("Generator %s not defined"%i) return v[i] def smith_form_gen(self, i): @@ -1152,7 +1152,7 @@ def smith_form_gen(self, i): """ v = self.smith_form_gens() if i < 0 or i >= len(v): - raise ValueError, "Smith form generator %s not defined"%i + raise ValueError("Smith form generator %s not defined"%i) return v[i] def optimized(self): @@ -1388,7 +1388,7 @@ def _hom_general(self, im_gens, check=True): r = A.hom([x.lift() for x in im_gens], N.V()) if check: if not r(B).is_submodule(N.W()): - raise ValueError, "Images do not determine a valid homomorphism" + raise ValueError("Images do not determine a valid homomorphism") smith_images = Sequence([N(r(q.lift(x.lift()))) for x in self.smith_form_gens()]) return self._hom_from_smith(smith_images, check=DEBUG) @@ -1417,7 +1417,7 @@ def _hom_from_smith(self, im_smith_gens, check=True): Morphism from module over Integer Ring with invariants (3,) to module with invariants (3,) that sends the generators to [(1), (1)] """ if len(im_smith_gens) != len(self.smith_form_gens()): - raise ValueError, "im_gens must have length the same as self.smith_form_gens()" + raise ValueError("im_gens must have length the same as self.smith_form_gens()") # replace self by representation in which smith-gens g_i are a basis for V. M, _ = self.optimized() @@ -1521,10 +1521,10 @@ def __iter__(self): True """ if self.base_ring() != ZZ: - raise NotImplementedError, "only implemented over ZZ" + raise NotImplementedError("only implemented over ZZ") v = self.invariants() if 0 in v: - raise NotImplementedError, "currently self must be finite to iterate over" + raise NotImplementedError("currently self must be finite to iterate over") B = self.optimized()[0].V().basis_matrix() V = self.base_ring()**B.nrows() from sage.misc.mrange import cartesian_product_iterator diff --git a/src/sage/modules/fg_pid/fgp_morphism.py b/src/sage/modules/fg_pid/fgp_morphism.py index a2602761308..04a57f59b0c 100644 --- a/src/sage/modules/fg_pid/fgp_morphism.py +++ b/src/sage/modules/fg_pid/fgp_morphism.py @@ -105,14 +105,14 @@ def __init__(self, parent, phi, check=True): MO, _ = M.optimized() if phi.domain() != MO.V(): - raise ValueError, "domain of phi must be the covering module for the optimized covering module of the domain" + raise ValueError("domain of phi must be the covering module for the optimized covering module of the domain") if phi.codomain() != N.V(): - raise ValueError, "codomain of phi must be the covering module the codomain." + raise ValueError("codomain of phi must be the covering module the codomain.") # check that MO.W() gets sent into N.W() # todo (optimize): this is slow: for x in MO.W().basis(): if phi(x) not in N.W(): - raise ValueError, "phi must send optimized submodule of M.W() into N.W()" + raise ValueError("phi must send optimized submodule of M.W() into N.W()") self._phi = phi def _repr_(self): @@ -276,7 +276,7 @@ def __call__(self, x): from fgp_module import is_FGP_Module if is_FGP_Module(x): if not x.is_submodule(self.domain()): - raise ValueError, "x must be a submodule or element of the domain" + raise ValueError("x must be a submodule or element of the domain") # perhaps can be optimized with a matrix multiply; but note # the subtlety of optimized representations. return self.codomain().submodule([self(y) for y in x.smith_form_gens()]) @@ -353,9 +353,9 @@ def inverse_image(self, A): """ from fgp_module import is_FGP_Module if not is_FGP_Module(A): - raise TypeError, "A must be a finitely generated quotient module" + raise TypeError("A must be a finitely generated quotient module") if not A.is_submodule(self.codomain()): - raise ValueError, "A must be a submodule of the codomain" + raise ValueError("A must be a submodule of the codomain") V = self._phi.inverse_image(A.V()) D = self.domain() V = D.W() + V @@ -438,7 +438,7 @@ def lift(self, x): if z.denominator() != 1: raise ValueError except ValueError: - raise ValueError, "no lift of element to domain" + raise ValueError("no lift of element to domain") # Write back in terms of rows of B, and delete rows not corresponding to A, # since those corresponding to relations diff --git a/src/sage/modules/free_module.py b/src/sage/modules/free_module.py index a61b433d45c..0305916c4b6 100644 --- a/src/sage/modules/free_module.py +++ b/src/sage/modules/free_module.py @@ -357,7 +357,7 @@ def create_object(self, version, key): return FreeQuadraticModule(base_ring, rank, inner_product_matrix=inner_product_matrix, sparse=sparse) if not isinstance(sparse,bool): - raise TypeError, "Argument sparse (= %s) must be True or False" % sparse + raise TypeError("Argument sparse (= %s) must be True or False" % sparse) if not (hasattr(base_ring,'is_commutative') and base_ring.is_commutative()): warn("""You are constructing a free module @@ -425,9 +425,9 @@ def VectorSpace(K, dimension, sparse=False, inner_product_matrix=None): TypeError: Argument K (= Integer Ring) must be a field. """ if not K.is_field(): - raise TypeError, "Argument K (= %s) must be a field." % K + raise TypeError("Argument K (= %s) must be a field." % K) if not sparse in (True,False): - raise TypeError, "Argument sparse (= %s) must be a boolean."%sparse + raise TypeError("Argument sparse (= %s) must be a boolean."%sparse) return FreeModule(K, rank=dimension, sparse=sparse, inner_product_matrix=inner_product_matrix) ############################################################################### @@ -694,10 +694,10 @@ def __init__(self, base_ring, rank, degree, sparse=False): done from the right side.""") rank = sage.rings.integer.Integer(rank) if rank < 0: - raise ValueError, "rank (=%s) must be nonnegative"%rank + raise ValueError("rank (=%s) must be nonnegative"%rank) degree = sage.rings.integer.Integer(degree) if degree < 0: - raise ValueError, "degree (=%s) must be nonnegative"%degree + raise ValueError("degree (=%s) must be nonnegative"%degree) from sage.categories.all import Fields, FreeModules, VectorSpaces if base_ring in Fields(): category = VectorSpaces(base_ring) @@ -956,7 +956,7 @@ def __call__(self, x, coerce=True, copy=True, check=True): if d not in R: raise ArithmeticError except ArithmeticError: - raise TypeError, "element (= %s) is not in free module"%(x,) + raise TypeError("element (= %s) is not in free module"%(x,)) return self._element_class(self, x, coerce, copy) def is_submodule(self, other): @@ -1078,7 +1078,7 @@ def _coerce_impl(self, x): # so we cache it. if self._has_coerce_map_from_space(x.parent()): return self(x) - raise TypeError, "Automatic coercion supported only for vectors or 0." + raise TypeError("Automatic coercion supported only for vectors or 0.") def __contains__(self, v): r""" @@ -1247,7 +1247,7 @@ def base_extend(self, R): """ if R.has_coerce_map_from(self.base_ring()): return self.change_ring(R) - raise TypeError, "Base extension of self (over '%s') to ring '%s' not defined."%(self.base_ring(),R) + raise TypeError("Base extension of self (over '%s') to ring '%s' not defined."%(self.base_ring(),R)) def basis(self): """ @@ -1374,9 +1374,9 @@ def direct_sum(self, other): [ 0 0 0 1/2 4 2] """ if not is_FreeModule(other): - raise TypeError, "other must be a free module" + raise TypeError("other must be a free module") if other.base_ring() != self.base_ring(): - raise TypeError, "base rins of self and other must be the same" + raise TypeError("base rins of self and other must be the same") return self.basis_matrix().block_sum(other.basis_matrix()).row_module(self.base_ring()) def coordinates(self, v, check=True): @@ -1507,7 +1507,7 @@ def coordinate_module(self, V): [ 0 0 3 0 -3 2 -1 2 -1 -4 2 -1 -2 1 2 0 0 -1 1] """ if not is_FreeModule(V): - raise ValueError, "V must be a free module" + raise ValueError("V must be a free module") A = self.basis_matrix() A = A.matrix_from_columns(A.pivots()).transpose() B = V.basis_matrix() @@ -1610,7 +1610,7 @@ def gen(self, i=0): TypeError: rational is not an integer """ if i < 0 or i >= self.rank(): - raise ValueError, "Generator %s not defined."%i + raise ValueError("Generator %s not defined."%i) return self.basis()[i] def gram_matrix(self): @@ -2225,9 +2225,9 @@ def __add__(self, other): if not isinstance(other, FreeModule_generic): if other == 0: return self - raise TypeError, "other (=%s) must be a free module"%other + raise TypeError("other (=%s) must be a free module"%other) if not (self.ambient_vector_space() == other.ambient_vector_space()): - raise TypeError, "ambient vector spaces must be equal" + raise TypeError("ambient vector spaces must be equal") return self.span(self.basis() + other.basis()) @@ -2317,13 +2317,13 @@ def index_in(self, other): +Infinity """ if not isinstance(other, FreeModule_generic): - raise TypeError, "other must be a free module" + raise TypeError("other must be a free module") if self.ambient_vector_space() != other.ambient_vector_space(): - raise ArithmeticError, "self and other must be embedded in the same ambient space." + raise ArithmeticError("self and other must be embedded in the same ambient space.") if self.base_ring() != other.base_ring(): - raise NotImplementedError, "lattice index only defined for modules over the same base ring." + raise NotImplementedError("lattice index only defined for modules over the same base ring.") if other.base_ring().is_field(): if self == other: @@ -2331,7 +2331,7 @@ def index_in(self, other): else: if self.is_subspace(other): return sage.rings.infinity.infinity - raise ArithmeticError, "self must be contained in the vector space spanned by other." + raise ArithmeticError("self must be contained in the vector space spanned by other.") try: C = [other.coordinates(b) for b in self.basis()] @@ -2427,15 +2427,15 @@ def intersection(self, other): """ if not isinstance(other, FreeModule_generic): - raise TypeError, "other must be a free module" + raise TypeError("other must be a free module") if self.ambient_vector_space() != other.ambient_vector_space(): - raise ArithmeticError, "self and other must be embedded in the same ambient space." + raise ArithmeticError("self and other must be embedded in the same ambient space.") if self.base_ring() != other.base_ring(): if other.base_ring().is_field(): return other.intersection(self) - raise NotImplementedError, "intersection of modules over different base rings (neither a field) is not implemented." + raise NotImplementedError("intersection of modules over different base rings (neither a field) is not implemented.") # dispense with the three easy cases if self == self.ambient_vector_space() or other.is_submodule(self): @@ -2680,13 +2680,13 @@ def span(self, gens, base_ring=None, check=True, already_echelonized=False): try: M = self.change_ring(base_ring) except TypeError: - raise ValueError, "Argument base_ring (= %s) is not compatible "%base_ring + \ - "with the base field (= %s)." % self.base_field() + raise ValueError("Argument base_ring (= %s) is not compatible "%base_ring + \ + "with the base field (= %s)." % self.base_field()) try: return M.span(gens) except TypeError: - raise ValueError, "Argument gens (= %s) is not compatible "%gens + \ - "with base_ring (= %s)."%base_ring + raise ValueError("Argument gens (= %s) is not compatible "%gens + \ + "with base_ring (= %s)."%base_ring) def submodule(self, gens, check=True, already_echelonized=False): r""" @@ -2760,7 +2760,7 @@ def submodule(self, gens, check=True, already_echelonized=False): V = self.span(gens, check=check, already_echelonized=already_echelonized) if check: if not V.is_submodule(self): - raise ArithmeticError, "Argument gens (= %s) does not generate a submodule of self."%gens + raise ArithmeticError("Argument gens (= %s) does not generate a submodule of self."%gens) return V def span_of_basis(self, basis, base_ring=None, check=True, already_echelonized=False): @@ -2817,13 +2817,13 @@ def span_of_basis(self, basis, base_ring=None, check=True, already_echelonized=F try: M = self.change_ring(base_ring) except TypeError: - raise ValueError, "Argument base_ring (= %s) is not compatible "%base_ring + \ - "with the base ring (= %s)."%self.base_ring() + raise ValueError("Argument base_ring (= %s) is not compatible "%base_ring + \ + "with the base ring (= %s)."%self.base_ring()) try: return M.span_of_basis(basis) except TypeError: - raise ValueError, "Argument gens (= %s) is not compatible "%basis + \ - "with base_ring (= %s)."%base_ring + raise ValueError("Argument gens (= %s) is not compatible "%basis + \ + "with base_ring (= %s)."%base_ring) def submodule_with_basis(self, basis, check=True, already_echelonized=False): """ @@ -2900,7 +2900,7 @@ def submodule_with_basis(self, basis, check=True, already_echelonized=False): V = self.span_of_basis(basis=basis, check=check, already_echelonized=already_echelonized) if check: if not V.is_submodule(self): - raise ArithmeticError, "The given basis does not generate a submodule of self." + raise ArithmeticError("The given basis does not generate a submodule of self.") return V def vector_space_span(self, gens, check=True): @@ -3018,12 +3018,12 @@ def quotient(self, sub, check=True): try: sub = self.submodule(sub) except (TypeError, ArithmeticError): - raise ArithmeticError, "sub must be a subspace of self" + raise ArithmeticError("sub must be a subspace of self") if self.base_ring() == sage.rings.integer_ring.ZZ: from fg_pid.fgp_module import FGP_Module return FGP_Module(self, sub, check=False) else: - raise NotImplementedError, "quotients of modules over rings other than fields or ZZ is not fully implemented" + raise NotImplementedError("quotients of modules over rings other than fields or ZZ is not fully implemented") def __div__(self, sub, check=True): """ @@ -3064,7 +3064,7 @@ def __init__(self, base_field, dimension, degree, sparse=False): """ if not isinstance(base_field, field.Field): - raise TypeError, "The base_field (=%s) must be a field"%base_field + raise TypeError("The base_field (=%s) must be a field"%base_field) FreeModule_generic_pid.__init__(self, base_field, dimension, degree, sparse=sparse) def _Hom_(self, Y, category): @@ -3178,10 +3178,10 @@ def __add__(self, other): if not isinstance(other, FreeModule_generic_field): if other == 0: return self - raise TypeError, "other must be a Vector Space" + raise TypeError("other must be a Vector Space") V = self.ambient_vector_space() if V != other.ambient_vector_space(): - raise ArithmeticError, "self and other must have the same ambient space" + raise ArithmeticError("self and other must have the same ambient space") return V.span(self.basis() + other.basis()) def echelonized_basis_matrix(self): @@ -3240,10 +3240,10 @@ def intersection(self, other): [] """ if not isinstance(other, FreeModule_generic): - raise TypeError, "other must be a free module" + raise TypeError("other must be a free module") if self.ambient_vector_space() != other.ambient_vector_space(): - raise ArithmeticError, "self and other must have the same ambient space." + raise ArithmeticError("self and other must have the same ambient space.") if self.rank() == 0 or other.rank() == 0: if self.base_ring().is_field(): @@ -3382,13 +3382,11 @@ def span(self, gens, base_ring=None, check=True, already_echelonized=False): try: M = self.ambient_module().change_ring(base_ring) except TypeError: - raise ValueError, \ - "Argument base_ring (= %s) is not compatible with the base field (= %s)." % (base_ring, self.base_field() ) + raise ValueError("Argument base_ring (= %s) is not compatible with the base field (= %s)." % (base_ring, self.base_field() )) try: return M.span(gens) except TypeError: - raise ValueError, \ - "Argument gens (= %s) is not compatible with base_ring (= %s)." % (gens, base_ring) + raise ValueError("Argument gens (= %s) is not compatible with base_ring (= %s)." % (gens, base_ring)) def span_of_basis(self, basis, base_ring=None, check=True, already_echelonized=False): r""" @@ -3442,14 +3440,12 @@ def span_of_basis(self, basis, base_ring=None, check=True, already_echelonized=F try: M = self.change_ring(base_ring) except TypeError: - raise ValueError, \ - "Argument base_ring (= %s) is not compatible with the base field (= %s)." % ( - base_ring, self.base_field() ) + raise ValueError("Argument base_ring (= %s) is not compatible with the base field (= %s)." % ( + base_ring, self.base_field() )) try: return M.span_of_basis(basis) except TypeError: - raise ValueError, \ - "Argument basis (= %s) is not compatible with base_ring (= %s)." % (basis, base_ring) + raise ValueError("Argument basis (= %s) is not compatible with base_ring (= %s)." % (basis, base_ring)) def subspace(self, gens, check=True, already_echelonized=False): """ @@ -3959,12 +3955,12 @@ def quotient(self, sub, check=True): # Calling is_submodule may be way too slow and repeat work done below. # It will be very desirable to somehow do this step better. if is_FreeModule(sub) and self.base_ring() != sub.base_ring(): - raise ValueError, "base rings must be the same" + raise ValueError("base rings must be the same") if check and (not is_FreeModule(sub) or not sub.is_subspace(self)): try: sub = self.subspace(sub) except (TypeError, ArithmeticError): - raise ArithmeticError, "sub must be a subspace of self" + raise ArithmeticError("sub must be a subspace of self") A, L = self.__quotient_matrices(sub) import quotient_module return quotient_module.FreeModule_ambient_field_quotient(self, sub, A, L) @@ -4119,7 +4115,7 @@ def quotient_abstract(self, sub, check=True): try: sub = self.subspace(sub) except (TypeError, ArithmeticError): - raise ArithmeticError, "sub must be a subspace of self" + raise ArithmeticError("sub must be a subspace of self") A, L = self.__quotient_matrices(sub) quomap = self.hom(A) @@ -5494,7 +5490,7 @@ def echelon_coordinates(self, v, check=True): if not isinstance(v, free_module_element.FreeModuleElement): v = self.ambient_vector_space()(v) elif v.degree() != self.degree(): - raise ArithmeticError, "vector is not in free module" + raise ArithmeticError("vector is not in free module") # Find coordinates of v with respect to rref basis. E = self.echelonized_basis_matrix() P = E.pivots() @@ -5509,7 +5505,7 @@ def echelon_coordinates(self, v, check=True): return x lc = E.linear_combination_of_rows(x) if lc != v and list(lc) != list(v): - raise ArithmeticError, "vector is not in free module" + raise ArithmeticError("vector is not in free module") return x def user_to_echelon_matrix(self): @@ -6512,12 +6508,12 @@ def echelon_coordinates(self, v, check=True): if not isinstance(v, free_module_element.FreeModuleElement): v = self.ambient_vector_space()(v) if v.degree() != self.degree(): - raise ArithmeticError, "v (=%s) is not in self"%v + raise ArithmeticError("v (=%s) is not in self"%v) E = self.echelonized_basis_matrix() P = E.pivots() if len(P) == 0: if check and v != 0: - raise ArithmeticError, "vector is not in free module" + raise ArithmeticError("vector is not in free module") return [] w = v.list_from_positions(P) if not check: @@ -6530,7 +6526,7 @@ def echelon_coordinates(self, v, check=True): # of v is not self. lc = E.linear_combination_of_rows(w) if lc != v: - raise ArithmeticError, "vector is not in free module" + raise ArithmeticError("vector is not in free module") return w def coordinate_vector(self, v, check=True): diff --git a/src/sage/modules/free_module_homspace.py b/src/sage/modules/free_module_homspace.py index 266e60aee01..de0b9cbaec7 100644 --- a/src/sage/modules/free_module_homspace.py +++ b/src/sage/modules/free_module_homspace.py @@ -296,5 +296,5 @@ def identity(self): if self.is_endomorphism_set(): return self(matrix.identity_matrix(self.base_ring(),self.domain().rank())) else: - raise TypeError, "Identity map only defined for endomorphisms. Try natural_map() instead." + raise TypeError("Identity map only defined for endomorphisms. Try natural_map() instead.") diff --git a/src/sage/modules/free_module_morphism.py b/src/sage/modules/free_module_morphism.py index 36c08ad837a..44f114c4b03 100644 --- a/src/sage/modules/free_module_morphism.py +++ b/src/sage/modules/free_module_morphism.py @@ -76,7 +76,7 @@ def __init__(self, parent, A): """ if not free_module_homspace.is_FreeModuleHomspace(parent): - raise TypeError, "parent (=%s) must be a free module hom space"%parent + raise TypeError("parent (=%s) must be a free module hom space"%parent) if isinstance(A, matrix_morphism.MatrixMorphism): A = A.matrix() A = parent._matrix_space()(A) @@ -318,7 +318,7 @@ def inverse_image(self, V): else: if not hasattr(A, 'hermite_form'): - raise NotImplementedError, "base ring (%s) must have hermite_form algorithm in order to compute inverse image"%R + raise NotImplementedError("base ring (%s) must have hermite_form algorithm in order to compute inverse image"%R) # 1. Compute H such that U*A = H = hnf(A) without zero # rows. What this "does" is find a basis for the image of @@ -410,18 +410,18 @@ def lift(self, x): try: C = A.solve_left(x) except ValueError: - raise ValueError, "element is not in the image" + raise ValueError("element is not in the image") else: # see inverse_image for similar code but with comments if not hasattr(A, 'hermite_form'): - raise NotImplementedError, "base ring (%s) must have hermite_form algorithm in order to compute inverse image"%R + raise NotImplementedError("base ring (%s) must have hermite_form algorithm in order to compute inverse image"%R) H, U = A.hermite_form(transformation=True,include_zero_rows=False) Y = H.solve_left(vector(self.codomain().coordinates(x))) C = Y*U try: t = self.domain().linear_combination_of_basis(C) except TypeError: - raise ValueError, "element is not in the image" + raise ValueError("element is not in the image") assert self(t) == x return t @@ -458,9 +458,9 @@ def eigenvalues(self,extend=True): if self.is_endomorphism(): return self.matrix().eigenvalues(extend=extend) else: - raise TypeError, "not an endomorphism" + raise TypeError("not an endomorphism") else: - raise NotImplementedError, "module must be a vector space" + raise NotImplementedError("module must be a vector space") def eigenvectors(self,extend=True): """ @@ -517,9 +517,9 @@ def eigenvectors(self,extend=True): resu.append((i[0],svectors,i[2])) return resu else: - raise TypeError, "not an endomorphism" + raise TypeError("not an endomorphism") else: - raise NotImplementedError, "module must be a vector space" + raise NotImplementedError("module must be a vector space") def minimal_polynomial(self,var='x'): r""" @@ -566,6 +566,6 @@ def minimal_polynomial(self,var='x'): if self.is_endomorphism(): return self.matrix().minpoly(var) else: - raise TypeError, "not an endomorphism" + raise TypeError("not an endomorphism") minpoly = minimal_polynomial diff --git a/src/sage/modules/free_quadratic_module.py b/src/sage/modules/free_quadratic_module.py index c34f347442f..aff82486c4f 100644 --- a/src/sage/modules/free_quadratic_module.py +++ b/src/sage/modules/free_quadratic_module.py @@ -138,12 +138,12 @@ def FreeQuadraticModule( rank = int(rank) if inner_product_matrix is None: - raise ValueError, "An inner_product_matrix must be specified." + raise ValueError("An inner_product_matrix must be specified.") # In order to use coercion into the inner_product_ring we need to pass # this ring into the vector classes. if inner_product_ring is not None: - raise NotImplementedError, "An inner_product_ring can not currently be defined." + raise NotImplementedError("An inner_product_ring can not currently be defined.") inner_product_matrix = sage.matrix.matrix_space.MatrixSpace(base_ring, rank)(inner_product_matrix) inner_product_matrix.set_immutable() @@ -156,7 +156,7 @@ def FreeQuadraticModule( return M if not base_ring.is_commutative(): - raise TypeError, "base_ring must be a commutative ring" + raise TypeError("base_ring must be a commutative ring") #elif not sparse and isinstance(base_ring,sage.rings.real_double.RealDoubleField_class): # M = RealDoubleQuadraticSpace_class(rank, inner_product_matrix=inner_product_matrix, sparse=False) @@ -210,9 +210,9 @@ def QuadraticSpace(K, dimension, inner_product_matrix, sparse=False): TypeError: Argument K (= Integer Ring) must be a field. """ if not K.is_field(): - raise TypeError, "Argument K (= %s) must be a field." % K + raise TypeError("Argument K (= %s) must be a field." % K) if not sparse in (True,False): - raise TypeError, "Argument sparse (= %s) must be a boolean."%sparse + raise TypeError("Argument sparse (= %s) must be a boolean."%sparse) return FreeQuadraticModule(K, rank=dimension, inner_product_matrix=inner_product_matrix, sparse=sparse) InnerProductSpace = QuadraticSpace @@ -619,7 +619,7 @@ def __init__(self, base_field, dimension, degree, inner_product_matrix, sparse=F [0 0 0 0 0 0 1] """ if not isinstance(base_field, field.Field): - raise TypeError, "The base_field (=%s) must be a field" % base_field + raise TypeError("The base_field (=%s) must be a field" % base_field) free_module.FreeModule_generic_field.__init__( self, base_field=base_field, dimension=dimension, degree=degree, sparse=sparse) #self._FreeQuadraticModule_generic_inner_product_matrix = inner_product_matrix @@ -652,7 +652,7 @@ def span(self, gens, check=True, already_echelonized=False): if free_module.is_FreeModule(gens): gens = gens.gens() if not isinstance(gens, (list, tuple)): - raise TypeError, "gens (=%s) must be a list or tuple"%gens + raise TypeError("gens (=%s) must be a list or tuple"%gens) return FreeQuadraticModule_submodule_field( self.ambient_module(), gens, diff --git a/src/sage/modules/matrix_morphism.py b/src/sage/modules/matrix_morphism.py index 8586ec8f16e..a056da9a530 100644 --- a/src/sage/modules/matrix_morphism.py +++ b/src/sage/modules/matrix_morphism.py @@ -92,7 +92,7 @@ def __init__(self, parent): True """ if not sage.categories.homset.is_Homset(parent): - raise TypeError, "parent must be a Hom space" + raise TypeError("parent must be a Hom space") sage.categories.morphism.Morphism.__init__(self, parent) def __cmp__(self, other): @@ -145,7 +145,7 @@ def __call__(self, x): if not hasattr(x, 'parent') or x.parent() != self.domain(): x = self.domain()(x) except TypeError: - raise TypeError, "%s must be coercible into %s"%(x,self.domain()) + raise TypeError("%s must be coercible into %s"%(x,self.domain())) if self.domain().is_ambient(): x = x.element() else: @@ -187,11 +187,11 @@ def __invert__(self): try: B = ~(self.matrix()) except ZeroDivisionError: - raise ZeroDivisionError, "matrix morphism not invertible" + raise ZeroDivisionError("matrix morphism not invertible") try: return self.parent().reversed()(B) except TypeError: - raise ZeroDivisionError, "matrix morphism not invertible" + raise ZeroDivisionError("matrix morphism not invertible") def inverse(self): r""" @@ -425,7 +425,7 @@ def __mul__(self, right): R = self.base_ring() return self.parent()(self.matrix() * R(right)) if self.domain() != right.codomain(): - raise TypeError, "Incompatible composition of morphisms: domain of left morphism must be codomain of right." + raise TypeError("Incompatible composition of morphisms: domain of left morphism must be codomain of right.") M = right.matrix() * self.matrix() return right.domain().Hom(self.codomain())(M) @@ -541,8 +541,8 @@ def characteristic_polynomial(self, var='x'): T^2 - 3*T + 2 """ if not self.is_endomorphism(): - raise ArithmeticError, "charpoly only defined for endomorphisms " +\ - "(i.e., domain = range)" + raise ArithmeticError("charpoly only defined for endomorphisms " +\ + "(i.e., domain = range)") return self.matrix().charpoly(var) charpoly = characteristic_polynomial @@ -570,7 +570,7 @@ def decomposition(self, *args, **kwds): ] """ if not self.is_endomorphism(): - raise ArithmeticError, "Matrix morphism must be an endomorphism." + raise ArithmeticError("Matrix morphism must be an endomorphism.") D = self.domain() E = self.matrix().decomposition(*args,**kwds) if D.is_ambient(): @@ -606,7 +606,7 @@ def det(self): 2 """ if not self.is_endomorphism(): - raise ArithmeticError, "Matrix morphism must be an endomorphism." + raise ArithmeticError("Matrix morphism must be an endomorphism.") return self.matrix().determinant() def fcp(self, var='x'): @@ -714,7 +714,7 @@ def matrix(self): ... NotImplementedError: this method must be overridden in the extension class """ - raise NotImplementedError, "this method must be overridden in the extension class" + raise NotImplementedError("this method must be overridden in the extension class") def rank(self): r""" @@ -1144,7 +1144,7 @@ def restrict(self, sub): True """ if not self.is_endomorphism(): - raise ArithmeticError, "matrix morphism must be an endomorphism" + raise ArithmeticError("matrix morphism must be an endomorphism") D = self.domain() C = self.codomain() if D is not C and (D.basis() != C.basis()): diff --git a/src/sage/modules/vector_space_morphism.py b/src/sage/modules/vector_space_morphism.py index 0796409c22c..63f43024377 100644 --- a/src/sage/modules/vector_space_morphism.py +++ b/src/sage/modules/vector_space_morphism.py @@ -849,7 +849,7 @@ def __init__(self, homspace, A): """ if not vector_space_homspace.is_VectorSpaceHomspace(homspace): - raise TypeError, 'homspace must be a vector space hom space, not {0}'.format(homspace) + raise TypeError('homspace must be a vector space hom space, not {0}'.format(homspace)) if isinstance(A, matrix_morphism.MatrixMorphism): A = A.matrix() if not is_Matrix(A): diff --git a/src/sage/monoids/free_abelian_monoid.py b/src/sage/monoids/free_abelian_monoid.py index 8bf138fe362..283edb909f9 100644 --- a/src/sage/monoids/free_abelian_monoid.py +++ b/src/sage/monoids/free_abelian_monoid.py @@ -128,9 +128,9 @@ class FreeAbelianMonoid_class(ParentWithGens): """ def __init__(self, n, names): if not isinstance(n, (int, long, Integer)): - raise TypeError, "n (=%s) must be an integer."%n + raise TypeError("n (=%s) must be an integer."%n) if n < 0: - raise ValueError, "n (=%s) must be nonnegative."%n + raise ValueError("n (=%s) must be nonnegative."%n) self.__ngens = int(n) assert not names is None self._assign_names(names) @@ -198,7 +198,7 @@ def gen(self, i=0): """ n = self.__ngens if i < 0 or not i < n: - raise IndexError, "Argument i (= %s) must be between 0 and %s."%(i, n-1) + raise IndexError("Argument i (= %s) must be between 0 and %s."%(i, n-1)) x = [ 0 for j in range(n) ] x[int(i)] = 1 return FreeAbelianMonoidElement(self,x) diff --git a/src/sage/monoids/free_abelian_monoid_element.py b/src/sage/monoids/free_abelian_monoid_element.py index c1a9f834293..c63ea6638a3 100644 --- a/src/sage/monoids/free_abelian_monoid_element.py +++ b/src/sage/monoids/free_abelian_monoid_element.py @@ -88,11 +88,10 @@ def __init__(self, F, x): self.__element_vector = [ 0 for i in range(n) ] elif isinstance(x, list): if len(x) != n: - raise IndexError, \ - "Argument length (= %s) must be %s."%(len(x), n) + raise IndexError("Argument length (= %s) must be %s."%(len(x), n)) self.__element_vector = x else: - raise TypeError, "Argument x (= %s) is of wrong type."%x + raise TypeError("Argument x (= %s) is of wrong type."%x) def __repr__(self): s = "" @@ -114,7 +113,7 @@ def __repr__(self): def __mul__(self, y): if not isinstance(y, FreeAbelianMonoidElement): - raise TypeError, "Argument y (= %s) is of wrong type."%y + raise TypeError("Argument y (= %s) is of wrong type."%y) M = self.parent() z = M(1) xelt = self.__element_vector @@ -144,9 +143,9 @@ def __pow__(self, n): """ if not isinstance(n, (int, long, Integer)): - raise TypeError, "Argument n (= %s) must be an integer."%n + raise TypeError("Argument n (= %s) must be an integer."%n) if n < 0: - raise IndexError, "Argument n (= %s) must be positive."%n + raise IndexError("Argument n (= %s) must be positive."%n) elif n == 1: return self z = self.parent()(1) diff --git a/src/sage/monoids/free_monoid.py b/src/sage/monoids/free_monoid.py index 1aa6709ac75..4aeeb4b42b5 100644 --- a/src/sage/monoids/free_monoid.py +++ b/src/sage/monoids/free_monoid.py @@ -129,9 +129,9 @@ def __init__(self, n, names=None): sage: TestSuite(M).run() """ if not isinstance(n, (int, long, Integer)): - raise TypeError, "n (=%s) must be an integer."%n + raise TypeError("n (=%s) must be an integer."%n) if n < 0: - raise ValueError, "n (=%s) must be nonnegative."%n + raise ValueError("n (=%s) must be nonnegative."%n) self.__ngens = int(n) #self._assign_names(names) Monoid_class.__init__(self,names) @@ -223,7 +223,7 @@ def gen(self,i=0): """ n = self.__ngens if i < 0 or not i < n: - raise IndexError, "Argument i (= %s) must be between 0 and %s."%(i, n-1) + raise IndexError("Argument i (= %s) must be between 0 and %s."%(i, n-1)) return self.element_class(self,[(Integer(i),Integer(1))]) def ngens(self): diff --git a/src/sage/monoids/free_monoid_element.py b/src/sage/monoids/free_monoid_element.py index 88a8ed6001f..7fecaf8f0d6 100644 --- a/src/sage/monoids/free_monoid_element.py +++ b/src/sage/monoids/free_monoid_element.py @@ -58,16 +58,16 @@ def __init__(self, F, x, check=True): if x == 1: self._element_list = [] else: - raise TypeError, "Argument x (= %s) is of the wrong type."%x + raise TypeError("Argument x (= %s) is of the wrong type."%x) elif isinstance(x, list): if check: x2 = [] for v in x: if not isinstance(v, tuple) and len(v) == 2: - raise TypeError, "x (= %s) must be a list of 2-tuples or 1."%x + raise TypeError("x (= %s) must be a list of 2-tuples or 1."%x) if not (isinstance(v[0], (int,long,Integer)) and \ isinstance(v[1], (int,long,Integer))): - raise TypeError, "x (= %s) must be a list of 2-tuples of integers or 1."%x + raise TypeError("x (= %s) must be a list of 2-tuples of integers or 1."%x) if len(x2) > 0 and v[0] == x2[len(x2)-1][0]: x2[len(x2)-1] = (v[0], v[1]+x2[len(x2)-1][1]) else: @@ -78,7 +78,7 @@ def __init__(self, F, x, check=True): else: # TODO: should have some other checks here... - raise TypeError, "Argument x (= %s) is of the wrong type."%x + raise TypeError("Argument x (= %s) is of the wrong type."%x) def __iter__(self): """ @@ -181,7 +181,7 @@ def __call__(self, *x, **kwds): - Joel B. Mohler (2007-10-27) """ if kwds and x: - raise ValueError, "must not specify both a keyword and positional argument" + raise ValueError("must not specify both a keyword and positional argument") P = self.parent() @@ -196,7 +196,7 @@ def __call__(self, *x, **kwds): x = x[0] if len(x) != self.parent().ngens(): - raise ValueError, "must specify as many values as generators in parent" + raise ValueError("must specify as many values as generators in parent") # I don't start with 0, because I don't want to preclude evaluation with #arbitrary objects (e.g. matrices) because of funny coercion. diff --git a/src/sage/monoids/string_ops.py b/src/sage/monoids/string_ops.py index b6f73862e21..7c24f14911c 100644 --- a/src/sage/monoids/string_ops.py +++ b/src/sage/monoids/string_ops.py @@ -19,7 +19,7 @@ def strip_encoding(S): 'THECATINTHEHAT' """ if not isinstance(S,str): - raise TypeError, "Argument S (= %s) must be a string." + raise TypeError("Argument S (= %s) must be a string.") X = '' for i in range(len(S)): C = S[i] @@ -48,7 +48,7 @@ def frequency_distribution(S, n=1, field=None): else: P[c] = eps return DiscreteProbabilitySpace(S,P,field) - raise TypeError, "Argument S (= %s) must be a string, list, or tuple." + raise TypeError("Argument S (= %s) must be a string, list, or tuple.") def coincidence_index(S,n=1): """ @@ -62,7 +62,7 @@ def coincidence_index(S,n=1): try: S.coincidence_index(n) except AttributeError: - raise TypeError, "Argument S (= %s) must be a string." + raise TypeError("Argument S (= %s) must be a string.") S = strip_encoding(S) N = len(S)-n+1 X = {} @@ -88,18 +88,18 @@ def coincidence_discriminant(S,n=2): 0.0827001855677322 """ if not isinstance(S,(list,tuple)): - raise TypeError, "Argument S (= %s) must be a list or tuple" % S + raise TypeError("Argument S (= %s) must be a list or tuple" % S) if n != 2: - raise ValueError, "Argument n (= %s) is only implemented for n = 2" % n + raise ValueError("Argument n (= %s) is only implemented for n = 2" % n) truth = True for bool in ( isinstance(c,(str,StringMonoidElement)) for c in S ): truth = truth and bool if not truth: - raise TypeError, "Argument S (= %s) must be a list of strings." + raise TypeError("Argument S (= %s) must be a list of strings.") for bool in ( len(c) == n for c in S ): truth = truth and bool if not truth: - raise ValueError, "Argument S (= %s) must be a list of strings of length 2" % S + raise ValueError("Argument S (= %s) must be a list of strings of length 2" % S) X1 = [ frequency_distribution([ s[i] for s in S]) for i in range(2) ] XX = frequency_distribution(S) if isinstance(S[0],StringMonoidElement): diff --git a/src/sage/numerical/knapsack.py b/src/sage/numerical/knapsack.py index fb8af43e83d..836305ffefa 100644 --- a/src/sage/numerical/knapsack.py +++ b/src/sage/numerical/knapsack.py @@ -169,7 +169,7 @@ def __init__(self, seq=None): if self.is_superincreasing(seq): self._seq = seq else: - raise ValueError, "seq must be a super-increasing sequence" + raise ValueError("seq must be a super-increasing sequence") def __cmp__(self, other): r""" @@ -271,9 +271,9 @@ def largest_less_than(self, N): floor = Function_floor() # input error handling if len(self._seq) == 0: - raise TypeError, "self must be a non-empty list of integers." + raise TypeError("self must be a non-empty list of integers.") if (not isinstance(N, Integer)) and (not isinstance(N, int)): - raise TypeError, "N (= %s) must be an integer." % N + raise TypeError("N (= %s) must be an integer." % N) # halving the list at each iteration, just like binary search # TODO: some error handling to ensure that self only contains integers? @@ -414,15 +414,15 @@ def is_superincreasing(self, seq=None): return False # so now self is known to represent a non-empty sequence if (not isinstance(self._seq[0], Integer)) and (not isinstance(self._seq[0], int)): - raise TypeError, "Element e (= %s) of self must be a non-negative integer." % self._seq[0] + raise TypeError("Element e (= %s) of self must be a non-negative integer." % self._seq[0]) if self._seq[0] < 0: - raise TypeError, "Element e (= %s) of self must be a non-negative integer." % self._seq[0] + raise TypeError("Element e (= %s) of self must be a non-negative integer." % self._seq[0]) cumSum = self._seq[0] # the cumulative sum of the sequence represented by self for e in self._seq[1:]: if (not isinstance(e, Integer)) and (not isinstance(e, int)): - raise TypeError, "Element e (= %s) of self must be a non-negative integer." % e + raise TypeError("Element e (= %s) of self must be a non-negative integer." % e) if e < 0: - raise TypeError, "Element e (= %s) of self must be a non-negative integer." % e + raise TypeError("Element e (= %s) of self must be a non-negative integer." % e) if e <= cumSum: return False cumSum += e @@ -434,15 +434,15 @@ def is_superincreasing(self, seq=None): return False # so now seq is known to represent a non-empty sequence if (not isinstance(seq[0], Integer)) and (not isinstance(seq[0], int)): - raise TypeError, "Element e (= %s) of seq must be a non-negative integer." % seq[0] + raise TypeError("Element e (= %s) of seq must be a non-negative integer." % seq[0]) if seq[0] < 0: - raise TypeError, "Element e (= %s) of seq must be a non-negative integer." % seq[0] + raise TypeError("Element e (= %s) of seq must be a non-negative integer." % seq[0]) cumSum = seq[0] # the cumulative sum of the sequence seq for e in seq[1:]: if (not isinstance(e, Integer)) and (not isinstance(e, int)): - raise TypeError, "Element e (= %s) of seq must be a non-negative integer." % e + raise TypeError("Element e (= %s) of seq must be a non-negative integer." % e) if e < 0: - raise TypeError, "Element e (= %s) of seq must be a non-negative integer." % e + raise TypeError("Element e (= %s) of seq must be a non-negative integer." % e) if e <= cumSum: return False cumSum += e @@ -527,11 +527,11 @@ def subset_sum(self, N): """ # input error handling if not self.is_superincreasing(): - raise TypeError, "self is not super-increasing. Only super-increasing sequences are currently supported." + raise TypeError("self is not super-increasing. Only super-increasing sequences are currently supported.") if (not isinstance(N, Integer)) and (not isinstance(N, int)): - raise TypeError, "N (= %s) must be a non-negative integer." % N + raise TypeError("N (= %s) must be a non-negative integer." % N) if N < 0: - raise TypeError, "N (= %s) must be a non-negative integer." % N + raise TypeError("N (= %s) must be a non-negative integer." % N) # solve subset sum problem for super-increasing sequence candidates = [] diff --git a/src/sage/parallel/decorate.py b/src/sage/parallel/decorate.py index f5b3bacfc0b..a87bf7bc581 100644 --- a/src/sage/parallel/decorate.py +++ b/src/sage/parallel/decorate.py @@ -80,7 +80,7 @@ def __init__(self, p_iter='fork', ncpus=None, **kwds): elif p_iter == 'reference': self.p_iter = p_iter_reference elif isinstance(p_iter, str): - raise ValueError, "unknown iterator '%s'" % p_iter + raise ValueError("unknown iterator '%s'" % p_iter) else: if self.p_iter is None: self.p_iter = p_iter diff --git a/src/sage/parallel/use_fork.py b/src/sage/parallel/use_fork.py index 35982d9b5dd..f54faa7aceb 100644 --- a/src/sage/parallel/use_fork.py +++ b/src/sage/parallel/use_fork.py @@ -58,7 +58,7 @@ def __init__(self, ncpus, timeout=0, verbose=False, reset_interfaces=True): """ self.ncpus = int(ncpus) if self.ncpus != ncpus: # check that there wasn't a roundoff - raise TypeError, "ncpus must be an integer" + raise TypeError("ncpus must be an integer") self.timeout = float(timeout) # require a float self.verbose = verbose self.reset_interfaces = reset_interfaces diff --git a/src/sage/plot/animate.py b/src/sage/plot/animate.py index 515698192a2..38ba89457a5 100644 --- a/src/sage/plot/animate.py +++ b/src/sage/plot/animate.py @@ -557,7 +557,7 @@ def gif(self, delay=20, savefile=None, iterations=0, show_path=False, msg = """ Error: ffmpeg does not appear to be installed. Download it from www.ffmpeg.org, or use 'convert' to produce gifs instead.""" - raise OSError, msg + raise OSError(msg) else: if not savefile: savefile = tmp_filename(ext='.gif') @@ -580,7 +580,7 @@ def gif(self, delay=20, savefile=None, iterations=0, show_path=False, the animate command can be saved in PNG image format. See www.imagemagick.org and www.ffmpeg.org for more information.""" - raise OSError, msg + raise OSError(msg) def show(self, delay=20, iterations=0): r""" @@ -741,7 +741,7 @@ def ffmpeg(self, savefile=None, show_path=False, output_format=None, msg = """Error: ffmpeg does not appear to be installed. Saving an animation to a movie file in any format other than GIF requires this software, so please install it and try again.""" - raise OSError, msg + raise OSError(msg) else: if savefile is None: if output_format is None: diff --git a/src/sage/plot/arc.py b/src/sage/plot/arc.py index c1a628e3a20..a040f7f81e3 100644 --- a/src/sage/plot/arc.py +++ b/src/sage/plot/arc.py @@ -81,7 +81,7 @@ def __init__(self, x, y, r1, r2, angle, s1, s2, options): self.r1 = float(r1) self.r2 = float(r2) if self.r1 <= 0 or self.r2 <= 0: - raise ValueError, "the radii must be positive real numbers." + raise ValueError("the radii must be positive real numbers.") self.angle = float(angle) self.s1 = float(s1) @@ -371,7 +371,7 @@ def arc(center, r1, r2=None, angle=0.0, sector=(0.0,2*pi), **options): g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) if len(sector) != 2: - raise ValueError, "the sector must consist of two angles" + raise ValueError("the sector must consist of two angles") g.add_primitive(Arc( center[0],center[1], r1,r2, diff --git a/src/sage/plot/bezier_path.py b/src/sage/plot/bezier_path.py index 949b0678134..f223a59efe0 100644 --- a/src/sage/plot/bezier_path.py +++ b/src/sage/plot/bezier_path.py @@ -112,7 +112,7 @@ def _plot3d_options(self, options=None): del options['thickness'] if 'fill' in options: if options['fill']: - raise NotImplementedError, "Invalid 3d fill style. Must set fill to False." + raise NotImplementedError("Invalid 3d fill style. Must set fill to False.") del options['fill'] if 'linestyle' in options: if options['linestyle'] not in ('solid', '-'): diff --git a/src/sage/plot/circle.py b/src/sage/plot/circle.py index 878231e0792..8eec2a06e97 100644 --- a/src/sage/plot/circle.py +++ b/src/sage/plot/circle.py @@ -354,4 +354,4 @@ def circle(center, radius, **options): elif len(center)==3: return g[0].plot3d(z=center[2]) else: - raise ValueError, 'The center of a plotted circle should have two or three coordinates.' + raise ValueError('The center of a plotted circle should have two or three coordinates.') diff --git a/src/sage/plot/contour_plot.py b/src/sage/plot/contour_plot.py index d5ea7a8d67a..ef47039ea21 100644 --- a/src/sage/plot/contour_plot.py +++ b/src/sage/plot/contour_plot.py @@ -684,7 +684,7 @@ def implicit_plot(f, xrange, yrange, **options): from sage.symbolic.expression import is_SymbolicEquation if is_SymbolicEquation(f): if f.operator() != operator.eq: - raise ValueError, "input to implicit plot must be function or equation" + raise ValueError("input to implicit plot must be function or equation") f = f.lhs() - f.rhs() linewidths = options.pop('linewidth', None) linestyles = options.pop('linestyle', None) diff --git a/src/sage/plot/disk.py b/src/sage/plot/disk.py index d603e0010fe..6e103792681 100644 --- a/src/sage/plot/disk.py +++ b/src/sage/plot/disk.py @@ -316,4 +316,4 @@ def disk(point, radius, angle, **options): elif len(point)==3: return g[0].plot3d(z=point[2]) else: - raise ValueError, 'The center point of a plotted disk should have two or three coordinates.' + raise ValueError('The center point of a plotted disk should have two or three coordinates.') diff --git a/src/sage/plot/ellipse.py b/src/sage/plot/ellipse.py index 2ab5633c552..52f947ade29 100644 --- a/src/sage/plot/ellipse.py +++ b/src/sage/plot/ellipse.py @@ -63,7 +63,7 @@ def __init__(self, x, y, r1, r2, angle, options): self.r1 = float(r1) self.r2 = float(r2) if self.r1 <= 0 or self.r2 <= 0: - raise ValueError, "both radii must be positive" + raise ValueError("both radii must be positive") self.angle = fmod(angle,2*pi) if self.angle < 0: self.angle += 2*pi GraphicPrimitive.__init__(self, options) @@ -315,4 +315,4 @@ def ellipse(center, r1, r2, angle=0, **options): if len(center)==2: return g elif len(center)==3: - raise NotImplementedError, "plotting ellipse in 3D is not implemented" + raise NotImplementedError("plotting ellipse in 3D is not implemented") diff --git a/src/sage/plot/graphics.py b/src/sage/plot/graphics.py index 549ee2dbd15..036b5860d27 100644 --- a/src/sage/plot/graphics.py +++ b/src/sage/plot/graphics.py @@ -195,7 +195,7 @@ def set_aspect_ratio(self, ratio): if ratio != 'auto' and ratio != 'automatic': ratio = float(ratio) if ratio <= 0: - raise ValueError, "the aspect ratio must be positive or 'automatic'" + raise ValueError("the aspect ratio must be positive or 'automatic'") else: ratio = 'automatic' self._extra_kwds['aspect_ratio'] = ratio @@ -636,9 +636,9 @@ def axes_labels(self, l=None): self._axes_labels = None return self._axes_labels if not isinstance(l, (list, tuple)): - raise TypeError, "l must be a list or tuple" + raise TypeError("l must be a list or tuple") if len(l) != 2: - raise ValueError, "l must have length 2" + raise ValueError("l must have length 2") self._axes_labels = tuple(l) def axes_label_color(self, c=None): @@ -915,7 +915,7 @@ def __setitem__(self, i, x): """ from sage.plot.primitive import GraphicPrimitive if not isinstance(x, GraphicPrimitive): - raise TypeError, "x must be a GraphicPrimitive" + raise TypeError("x must be a GraphicPrimitive") self._objects[int(i)] = x def __radd__(self, other): @@ -1008,7 +1008,7 @@ def __add__(self, other): from sage.plot.plot3d.base import Graphics3d if isinstance(other, Graphics3d): return self.plot3d() + other - raise TypeError, "other (=%s) must be a Graphics objects"%other + raise TypeError("other (=%s) must be a Graphics objects"%other) g = Graphics() g._objects = self._objects + other._objects g._show_legend = self._show_legend or other._show_legend @@ -2830,7 +2830,7 @@ def __init__(self, array): TypeError: every element of array must be a Graphics object """ if not isinstance(array, (list, tuple)): - raise TypeError,"array (=%s) must be a list of lists of Graphics objects"%(array) + raise TypeError("array (=%s) must be a list of lists of Graphics objects"%(array)) array = list(array) self._glist = [] self._rows = len(array) @@ -2844,10 +2844,10 @@ def __init__(self, array): self._dims = self._rows*self._cols for row in array: #basically flatten the list if not isinstance(row, (list, tuple)) or len(row) != self._cols: - raise TypeError,"array (=%s) must be a list of lists of Graphics objects"%(array) + raise TypeError("array (=%s) must be a list of lists of Graphics objects"%(array)) for g in row: if not isinstance(g, Graphics): - raise TypeError, "every element of array must be a Graphics object" + raise TypeError("every element of array must be a Graphics object") self._glist.append(g) self._figsize = None diff --git a/src/sage/plot/matrix_plot.py b/src/sage/plot/matrix_plot.py index c15f2f7a1d9..cd563f5e464 100644 --- a/src/sage/plot/matrix_plot.py +++ b/src/sage/plot/matrix_plot.py @@ -466,7 +466,7 @@ def matrix_plot(mat, **options): try: data = np.asarray([d for _,d in entries], dtype=float) except Exception: - raise ValueError, "can not convert entries to floating point numbers" + raise ValueError("can not convert entries to floating point numbers") positions = np.asarray([[row for (row,col),_ in entries], [col for (row,col),_ in entries]], dtype=int) mat = scipysparse.coo_matrix((data,positions), shape=(mat.nrows(), mat.ncols())) @@ -484,12 +484,12 @@ def matrix_plot(mat, **options): else: xy_data_array = np.asarray(mat, dtype = float) except TypeError: - raise TypeError, "mat must be a Matrix or a two dimensional array" + raise TypeError("mat must be a Matrix or a two dimensional array") except ValueError: - raise ValueError, "can not convert entries to floating point numbers" + raise ValueError("can not convert entries to floating point numbers") if len(xy_data_array.shape) < 2: - raise TypeError, "mat must be a Matrix or a two dimensional array" + raise TypeError("mat must be a Matrix or a two dimensional array") xrange = (0, xy_data_array.shape[1]) yrange = (0, xy_data_array.shape[0]) diff --git a/src/sage/plot/misc.py b/src/sage/plot/misc.py index 79c2711b828..86a5a157016 100644 --- a/src/sage/plot/misc.py +++ b/src/sage/plot/misc.py @@ -100,13 +100,13 @@ def setup_for_eval_on_grid(funcs, ranges, plot_points=None, return_vars=False): (, [(1.0, -1.0, 2.0), (-1.0, 1.0, 2.0)], [y, x]) """ if max(map(len, ranges)) != min(map(len, ranges)): - raise ValueError, "Some variable ranges specify variables while others do not" + raise ValueError("Some variable ranges specify variables while others do not") if len(ranges[0])==3: vars = [r[0] for r in ranges] ranges = [r[1:] for r in ranges] if len(set(vars))1: @@ -126,12 +126,12 @@ def setup_for_eval_on_grid(funcs, ranges, plot_points=None, return_vars=False): if not isinstance(plot_points, (list, tuple)): plot_points = [plot_points]*len(ranges) elif len(plot_points)!=nargs: - raise ValueError, "plot_points must be either an integer or a list of integers, one for each range" + raise ValueError("plot_points must be either an integer or a list of integers, one for each range") plot_points = [int(p) if p>=2 else 2 for p in plot_points] range_steps = [abs(range[1] - range[0])/(p-1) for range, p in zip(ranges, plot_points)] if min(range_steps) == float(0): - raise ValueError, "plot start point and end point must be different" + raise ValueError("plot start point and end point must be different") options={} if nargs==1: diff --git a/src/sage/plot/plot.py b/src/sage/plot/plot.py index 7d0107fa583..e905e501e94 100644 --- a/src/sage/plot/plot.py +++ b/src/sage/plot/plot.py @@ -567,7 +567,7 @@ def xydata_from_point_list(points): pass if len(points)>0 and len(list(points[0]))!=2: - raise ValueError, "points must have 2 coordinates in a 2d line" + raise ValueError("points must have 2 coordinates in a 2d line") xdata = [float(z[0]) for z in points] @@ -1562,7 +1562,7 @@ def parametric_plot(funcs, *args, **kwargs): num_vars=len(sage.plot.misc.unify_arguments(funcs)[0]) if num_vars>num_ranges: - raise ValueError, "there are more variables than variable ranges" + raise ValueError("there are more variables than variable ranges") # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. @@ -1578,7 +1578,7 @@ def parametric_plot(funcs, *args, **kwargs): elif (num_funcs == 3 and num_ranges <= 2): return sage.plot.plot3d.parametric_plot3d.parametric_plot3d(funcs, *args, **kwargs) else: - raise ValueError, "the number of functions and the number of variable ranges is not a supported combination for a 2d or 3d parametric plots" + raise ValueError("the number of functions and the number of variable ranges is not a supported combination for a 2d or 3d parametric plots") @options(aspect_ratio=1.0) def polar_plot(funcs, *args, **kwds): @@ -2203,9 +2203,9 @@ def var_and_list_of_values(v, plot_points): deprecation(7008, "var_and_list_of_values is deprecated. Please use sage.plot.misc.setup_for_eval_on_grid; note that that function has slightly different calling and return conventions which make it more generally applicable") plot_points = int(plot_points) if plot_points < 2: - raise ValueError, "plot_points must be greater than 1" + raise ValueError("plot_points must be greater than 1") if not isinstance(v, (tuple, list)): - raise TypeError, "v must be a tuple or list" + raise TypeError("v must be a tuple or list") if len(v) == 3: var = v[0] a, b = v[1], v[2] @@ -2213,7 +2213,7 @@ def var_and_list_of_values(v, plot_points): var = None a, b = v else: - raise ValueError, "parametric value range must be a list or tuple of length 2 or 3." + raise ValueError("parametric value range must be a list or tuple of length 2 or 3.") a = float(a) b = float(b) diff --git a/src/sage/plot/plot3d/list_plot3d.py b/src/sage/plot/plot3d/list_plot3d.py index 49f4a6e6e3d..f7e2c70590a 100644 --- a/src/sage/plot/plot3d/list_plot3d.py +++ b/src/sage/plot/plot3d/list_plot3d.py @@ -193,7 +193,7 @@ def list_plot3d(v, interpolation_type='default', texture="automatic", point_list return list_plot3d_tuples(v,interpolation_type,texture=texture, **kwds) else: return list_plot3d_array_of_arrays(v, interpolation_type,texture, **kwds) - raise TypeError, "v must be a matrix or list" + raise TypeError("v must be a matrix or list") def list_plot3d_matrix(m, texture, **kwds): """ @@ -357,7 +357,7 @@ def list_plot3d_tuples(v,interpolation_type, texture, **kwds): from plot3d import plot3d if len(v)<3: - raise ValueError, "We need at least 3 points to perform the interpolation" + raise ValueError("We need at least 3 points to perform the interpolation") x=[float(p[0]) for p in v] y=[float(p[1]) for p in v] @@ -386,7 +386,7 @@ def list_plot3d_tuples(v,interpolation_type, texture, **kwds): for j in range(i+1,len(x)): if x[i]==x[j] and y[i]==y[j]: if z[i]!=z[j]: - raise ValueError, "Two points with same x,y coordinates and different z coordinates were given. Interpolation cannot handle this." + raise ValueError("Two points with same x,y coordinates and different z coordinates were given. Interpolation cannot handle this.") elif z[i]==z[j]: drop_list.append(j) diff --git a/src/sage/plot/plot3d/parametric_plot3d.py b/src/sage/plot/plot3d/parametric_plot3d.py index e1edfb404a5..9a2d0f19b23 100644 --- a/src/sage/plot/plot3d/parametric_plot3d.py +++ b/src/sage/plot/plot3d/parametric_plot3d.py @@ -501,7 +501,7 @@ def parametric_plot3d(f, urange, vrange=None, plot_points="automatic", boundary_ return sum([parametric_plot3d(v, urange, vrange, plot_points=plot_points, **kwds) for v in f]) if not isinstance(f, (tuple, list)) or len(f) != 3: - raise ValueError, "f must be a list, tuple, or vector of length 3" + raise ValueError("f must be a list, tuple, or vector of length 3") if vrange is None: if plot_points == "automatic": diff --git a/src/sage/plot/plot3d/plot3d.py b/src/sage/plot/plot3d/plot3d.py index 880248cc503..9ac8777716d 100644 --- a/src/sage/plot/plot3d/plot3d.py +++ b/src/sage/plot/plot3d/plot3d.py @@ -118,7 +118,7 @@ def __init__(self, dep_var, indep_vars): import inspect all_vars=inspect.getargspec(self.transform).args[1:] if set(all_vars) != set(indep_vars + [dep_var]): - raise ValueError, 'variables were specified incorrectly for this coordinate system; incorrect variables were %s'%list(set(all_vars).symmetric_difference(set(indep_vars+[dep_var]))) + raise ValueError('variables were specified incorrectly for this coordinate system; incorrect variables were %s'%list(set(all_vars).symmetric_difference(set(indep_vars+[dep_var])))) self.dep_var = dep_var self.indep_vars = indep_vars @@ -260,7 +260,7 @@ def to_cartesian(self, func, params=None): if params is None: params=['u','v'] else: - raise ValueError, "function is not callable" + raise ValueError("function is not callable") def subs_func(t): # We use eval so that the lambda function has the same # variable names as the original function @@ -816,13 +816,13 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): if isinstance(transformation, (tuple, list,Vector_callable_symbolic_dense)): if len(transformation)==3: if params is None: - raise ValueError, "must specify independent variable names in the ranges when using generic transformation" + raise ValueError("must specify independent variable names in the ranges when using generic transformation") indep_vars = params elif len(transformation)==4: indep_vars = transformation[3] transformation = transformation[0:3] else: - raise ValueError, "unknown transformation type" + raise ValueError("unknown transformation type") # find out which variable is the function variable by # eliminating the parameter variables. all_vars = set(sum([list(s.variables()) for s in transformation],[])) @@ -831,13 +831,13 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): dep_var = dep_var.pop() transformation = _ArbitraryCoordinates(transformation, dep_var, indep_vars) else: - raise ValueError, "unable to determine the function variable in the transform" + raise ValueError("unable to determine the function variable in the transform") if isinstance(transformation, _Coordinates): R = transformation.to_cartesian(f, params) return parametric_plot3d.parametric_plot3d(R, urange, vrange, **kwds) else: - raise ValueError, 'unknown transformation type' + raise ValueError('unknown transformation type') elif adaptive: P = plot3d_adaptive(f, urange, vrange, **kwds) else: diff --git a/src/sage/plot/plot3d/revolution_plot3d.py b/src/sage/plot/plot3d/revolution_plot3d.py index 90b39ab2e62..88ff04eff34 100644 --- a/src/sage/plot/plot3d/revolution_plot3d.py +++ b/src/sage/plot/plot3d/revolution_plot3d.py @@ -113,7 +113,7 @@ def revolution_plot3d(curve,trange,phirange=None,parallel_axis='z',axis=(0,0),pr if parallel_axis not in ['x','y','z']: - raise ValueError, "parallel_axis must be either 'x', 'y', or 'z'." + raise ValueError("parallel_axis must be either 'x', 'y', or 'z'.") vart=trange[0] diff --git a/src/sage/plot/plot3d/shapes2.py b/src/sage/plot/plot3d/shapes2.py index d0eef4610d8..feeecf159af 100644 --- a/src/sage/plot/plot3d/shapes2.py +++ b/src/sage/plot/plot3d/shapes2.py @@ -134,7 +134,7 @@ def line3d(points, thickness=1, radius=None, arrow_head=False, **kwds): """ points = list(points) if len(points) < 2: - raise ValueError, "there must be at least 2 points" + raise ValueError("there must be at least 2 points") for i in range(len(points)): x, y, z = points[i] points[i] = float(x), float(y), float(z) @@ -490,7 +490,7 @@ def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: - raise ValueError, "Absolute rulers only valid for axis-aligned paths" + raise ValueError("Absolute rulers only valid for axis-aligned paths") m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] @@ -797,7 +797,7 @@ def __init__(self, points, thickness=5, corner_cutoff=.5, arrow_head=False, **kw ([(1, 2, 3), (1, 2, 2), (-1, 2, 2), (-1, 3, 2)], False) """ if len(points) < 2: - raise ValueError, "there must be at least 2 points" + raise ValueError("there must be at least 2 points") PrimitiveObject.__init__(self, **kwds) self.points = points self.thickness = thickness diff --git a/src/sage/plot/plot3d/tachyon.py b/src/sage/plot/plot3d/tachyon.py index db7dfa063be..6d90fc7d510 100644 --- a/src/sage/plot/plot3d/tachyon.py +++ b/src/sage/plot/plot3d/tachyon.py @@ -476,7 +476,7 @@ def texfunc(self, type=0, center=(0,0,0), rotate=(0,0,0), scale=(1,1,1)): """ type = int(type) if type < 0 or type > 9: - raise ValueError, "type must be an integer between 0 and 9" + raise ValueError("type must be an integer between 0 and 9") return Texfunc(type,center,rotate,scale).str() def texture(self, name, ambient=0.2, diffuse=0.8, diff --git a/src/sage/plot/plot3d/tri_plot.py b/src/sage/plot/plot3d/tri_plot.py index 70a176e4709..013ce43348a 100644 --- a/src/sage/plot/plot3d/tri_plot.py +++ b/src/sage/plot/plot3d/tri_plot.py @@ -252,7 +252,7 @@ def __init__(self, triangle_factory, f, (min_x, max_x), (min_y, max_y), g = None self._max_bend = max_bend self._objects = [] if min(max_x - min_x, max_y - min_y) == 0: - raise ValueError, 'Plot rectangle is really a line. Make sure min_x != max_x and min_y != max_y.' + raise ValueError('Plot rectangle is really a line. Make sure min_x != max_x and min_y != max_y.') self._num_colors = num_colors if g is None: def fcn(x,y): diff --git a/src/sage/plot/point.py b/src/sage/plot/point.py index dc8f7b9d150..e2775be0595 100644 --- a/src/sage/plot/point.py +++ b/src/sage/plot/point.py @@ -122,7 +122,7 @@ def _plot3d_options(self, options=None): del options['size'] if 'faceted' in options: if options['faceted']: - raise NotImplementedError, "No 3d faceted points." + raise NotImplementedError("No 3d faceted points.") del options['faceted'] options_3d.update(GraphicPrimitive_xydata._plot3d_options(self, options)) return options_3d @@ -218,7 +218,7 @@ def plot3d(self, z=0, **kwds): else: return Graphics3dGroup(all) else: - raise ValueError, 'Incorrect number of heights given' + raise ValueError('Incorrect number of heights given') def _repr_(self): """ diff --git a/src/sage/plot/polygon.py b/src/sage/plot/polygon.py index 5851a2fff60..4358af4e009 100644 --- a/src/sage/plot/polygon.py +++ b/src/sage/plot/polygon.py @@ -225,7 +225,7 @@ def plot3d(self, z=0, **kwds): if len(zdata)==len(self.xdata): return IndexFaceSet([[(x, y, z) for x, y, z in zip(self.xdata, self.ydata, zdata)]], **options) else: - raise ValueError, 'Incorrect number of heights given' + raise ValueError('Incorrect number of heights given') def _render_on_subplot(self, subplot): """ diff --git a/src/sage/plot/primitive.py b/src/sage/plot/primitive.py index fee17eba974..cc11c7ab99b 100644 --- a/src/sage/plot/primitive.py +++ b/src/sage/plot/primitive.py @@ -80,7 +80,7 @@ def plot3d(self, **kwds): ... NotImplementedError: 3D plotting not implemented for Graphics primitive """ - raise NotImplementedError, "3D plotting not implemented for %s" % self._repr_() + raise NotImplementedError("3D plotting not implemented for %s" % self._repr_()) def _plot3d_options(self, options=None): """ diff --git a/src/sage/plot/text.py b/src/sage/plot/text.py index 4991ecfbdb3..98287debdb0 100644 --- a/src/sage/plot/text.py +++ b/src/sage/plot/text.py @@ -251,7 +251,7 @@ def text(string, xy, **options): x, y = xy except ValueError: if isinstance(xy, (list, tuple)) and len(xy) == 3: - raise ValueError, "use text3d instead for text in 3d" + raise ValueError("use text3d instead for text in 3d") raise from sage.plot.all import Graphics options['rgbcolor'] = to_mpl_color(options['rgbcolor']) diff --git a/src/sage/probability/random_variable.py b/src/sage/probability/random_variable.py index 5b28a05cbde..4a670e9d2f5 100644 --- a/src/sage/probability/random_variable.py +++ b/src/sage/probability/random_variable.py @@ -47,7 +47,7 @@ class RandomVariable_generic(ParentWithBase): """ def __init__(self, X, RR): if not is_ProbabilitySpace(X): - raise TypeError, "Argument X (= %s) must be a probability space" % X + raise TypeError("Argument X (= %s) must be a probability space" % X) ParentWithBase.__init__(self, X) self._codomain = RR @@ -75,9 +75,9 @@ def __init__(self, X, f, codomain = None, check = False): value for x in X is the discrete function on X """ if not is_DiscreteProbabilitySpace(X): - raise TypeError, "Argument X (= %s) must be a discrete probability space" % X + raise TypeError("Argument X (= %s) must be a discrete probability space" % X) if check: - raise NotImplementedError, "Not implemented" + raise NotImplementedError("Not implemented") if codomain is None: RR = RealField() else: @@ -185,8 +185,7 @@ def covariance(self, other): """ Omega = self.probability_space() if Omega != other.probability_space(): - raise ValueError, \ - "Argument other (= %s) must be defined on the same probability space." % other + raise ValueError("Argument other (= %s) must be defined on the same probability space." % other) muX = self.expectation() muY = other.expectation() cov = 0 @@ -209,8 +208,7 @@ def translation_covariance(self, other, map): """ Omega = self.probability_space() if Omega != other.probability_space(): - raise ValueError, \ - "Argument other (= %s) must be defined on the same probability space." % other + raise ValueError("Argument other (= %s) must be defined on the same probability space." % other) muX = self.expectation() muY = other.translation_expectation(map) cov = 0 @@ -258,8 +256,7 @@ def correlation(self, other): sigX = self.standard_deviation() sigY = other.standard_deviation() if sigX == 0 or sigY == 0: - raise ValueError, \ - "Correlation not defined if standard deviations are not both nonzero." + raise ValueError("Correlation not defined if standard deviations are not both nonzero.") return cov/(sigX*sigY) def translation_correlation(self, other, map): @@ -271,8 +268,7 @@ def translation_correlation(self, other, map): sigX = self.standard_deviation() sigY = other.translation_standard_deviation(map) if sigX == 0 or sigY == 0: - raise ValueError, \ - "Correlation not defined if standard deviations are not both nonzero." + raise ValueError("Correlation not defined if standard deviations are not both nonzero.") return cov/(sigX*sigY) ################################################################################ @@ -290,8 +286,7 @@ def __init__(self, domain, RR): if isinstance(domain, list): domain = tuple(domain) if not isinstance(domain, tuple): - raise TypeError, \ - "Argument domain (= %s) must be a list, tuple, or set containing." % domain + raise TypeError("Argument domain (= %s) must be a list, tuple, or set containing." % domain) self._domain = domain RandomVariable_generic.__init__(self, self, RR) @@ -338,15 +333,15 @@ def __init__(self, X, P, codomain = None, check = False): if codomain is None: codomain = RealField() if not is_RealField(codomain) and not is_RationalField(codomain): - raise TypeError, "Argument codomain (= %s) must be the reals or rationals" % codomain + raise TypeError("Argument codomain (= %s) must be the reals or rationals" % codomain) if check: one = sum([ P[x] for x in P.keys() ]) if is_RationalField(codomain): if not one == 1: - raise TypeError, "Argument P (= %s) does not define a probability function" + raise TypeError("Argument P (= %s) does not define a probability function") else: if not Abs(one-1) < 2^(-codomain.precision()+1): - raise TypeError, "Argument P (= %s) does not define a probability function" + raise TypeError("Argument P (= %s) does not define a probability function") ProbabilitySpace_generic.__init__(self, X, codomain) DiscreteRandomVariable.__init__(self, self, P, codomain, check) diff --git a/src/sage/quadratic_forms/binary_qf.py b/src/sage/quadratic_forms/binary_qf.py index 58f1a645bf1..5058d431ce8 100644 --- a/src/sage/quadratic_forms/binary_qf.py +++ b/src/sage/quadratic_forms/binary_qf.py @@ -115,7 +115,7 @@ def __init__(self, abc): if isinstance(abc, (list, tuple)): if len(abc) != 3: # Check we have three coefficients - raise TypeError, "Binary quadratic form must be given by a list of three coefficients" + raise TypeError("Binary quadratic form must be given by a list of three coefficients") self._a, self._b, self._c = [ZZ(x) for x in abc] else: f = abc @@ -127,7 +127,7 @@ def __init__(self, abc): x, y = f.parent().gens() self._a, self._b, self._c = [f.monomial_coefficient(mon) for mon in [x**2, x*y, y**2]] else: - raise TypeError, "Binary quadratic form must be given by a quadratic homogeneous bivariate integer polynomial" + raise TypeError("Binary quadratic form must be given by a quadratic homogeneous bivariate integer polynomial") def _pari_init_(self): """ @@ -175,7 +175,7 @@ def __mul__(self, right): """ if not isinstance(right, BinaryQF): - raise TypeError, "both self and right must be binary quadratic forms" + raise TypeError("both self and right must be binary quadratic forms") # There could be more elegant ways, but qfbcompraw isn't # wrapped yet in the PARI C library. We may as well settle # for the below, until somebody simply implements composition @@ -485,7 +485,7 @@ def is_weakly_reduced(self): True """ if self.discriminant() >= 0: - raise NotImplementedError, "only implemented for negative discriminants" + raise NotImplementedError("only implemented for negative discriminants") return (abs(self._b) <= self._a) and (self._a <= self._c) @cached_method @@ -513,7 +513,7 @@ def reduced_form(self): True """ if self.discriminant() >= 0 or self._a < 0: - raise NotImplementedError, "only implemented for positive definite forms" + raise NotImplementedError("only implemented for positive definite forms") if not self.is_reduced(): v = list(pari('Vec(qfbred(Qfb(%s,%s,%s)))'%(self._a,self._b,self._c))) return BinaryQF(v) @@ -540,7 +540,7 @@ def is_equivalent(self, right): False """ if not isinstance(right, BinaryQF): - raise TypeError, "right must be a binary quadratic form" + raise TypeError("right must be a binary quadratic form") return self.reduced_form() == right.reduced_form() @cached_method @@ -587,7 +587,7 @@ def complex_point(self): 1.00000000000000*I """ if self.discriminant() >= 0: - raise NotImplementedError, "only implemented for negative discriminant" + raise NotImplementedError("only implemented for negative discriminant") R = ZZ['x'] x = R.gen() Q1 = R(self.polynomial()(x,1)) @@ -719,7 +719,7 @@ def BinaryQF_reduced_representatives(D, primitive_only=False): """ D = ZZ(D) if not ( D < 0 and (D % 4 in [0,1])): - raise ValueError, "discriminant must be negative and congruent to 0 or 1 modulo 4" + raise ValueError("discriminant must be negative and congruent to 0 or 1 modulo 4") # For a fundamental discriminant all forms are primitive so we need not check: if primitive_only: diff --git a/src/sage/quadratic_forms/constructions.py b/src/sage/quadratic_forms/constructions.py index 9afe47fe1d4..90c7946003f 100644 --- a/src/sage/quadratic_forms/constructions.py +++ b/src/sage/quadratic_forms/constructions.py @@ -47,9 +47,9 @@ def BezoutianQuadraticForm(f, g): """ ## Check that f and g are polynomials with a common base ring if not is_Polynomial(f) or not is_Polynomial(g): - raise TypeError, "Oops! One of your inputs is not a polynomial. =(" + raise TypeError("Oops! One of your inputs is not a polynomial. =(") if f.base_ring() != g.base_ring(): ## TO DO: Change this to allow coercion! - raise TypeError, "Oops! These polynomials are not defined over the same coefficient ring." + raise TypeError("Oops! These polynomials are not defined over the same coefficient ring.") ## Initialize the quadratic form R = f.base_ring() @@ -91,7 +91,7 @@ def HyperbolicPlane_quadratic_form(R, r=1): r = ZZ(r) ## Check that the multiplicity is a natural number if r < 1: - raise TypeError, "The multiplicity r must be a natural number." + raise TypeError("The multiplicity r must be a natural number.") H = QuadraticForm(R, 2, [0, 1, 0]) return sum([H for i in range(r-1)], H) diff --git a/src/sage/quadratic_forms/extras.py b/src/sage/quadratic_forms/extras.py index cdaa53647af..5d145b76886 100644 --- a/src/sage/quadratic_forms/extras.py +++ b/src/sage/quadratic_forms/extras.py @@ -179,9 +179,9 @@ def least_quadratic_nonresidue(p): ## Deal with the prime p = 2 and |p| <= 1. if p1 == 2: - raise ValueError, "Oops! There are no quadratic non-residues in Z/2Z." + raise ValueError("Oops! There are no quadratic non-residues in Z/2Z.") if p1 < 2: - raise ValueError, "Oops! p must be a prime number > 2." + raise ValueError("Oops! p must be a prime number > 2.") ## Find the smallest non-residue mod p ## For 7/8 of primes the answer is 2, 3 or 5: @@ -193,7 +193,7 @@ def least_quadratic_nonresidue(p): return ZZ(5) ## default case (first needed for p=71): if not p.is_prime(): - raise ValueError, "Oops! p must be a prime number > 2." + raise ValueError("Oops! p must be a prime number > 2.") from sage.misc.misc import xsrange for r in xsrange(7,p): if legendre_symbol(r, p) == -1: diff --git a/src/sage/quadratic_forms/genera/genus.py b/src/sage/quadratic_forms/genera/genus.py index e9bacdd1123..14540e67e23 100644 --- a/src/sage/quadratic_forms/genera/genus.py +++ b/src/sage/quadratic_forms/genera/genus.py @@ -159,7 +159,7 @@ def is_2_adic_genus(genus_symbol_quintuple_list): ## Check that we have a quintuple (i.e. that p=2 and not p >2) if len(s) != 5: - raise TypeError, "The genus symbols are not quintuples, so it's not a genus symbol for the prime p=2." + raise TypeError("The genus symbols are not quintuples, so it's not a genus symbol for the prime p=2.") ## Check the Conway-Sloane conditions if s[1] == 1: @@ -517,7 +517,7 @@ def signature_pair_of_matrix(A): ## Check that the matrix is non-degenerate (i.e. no zero eigenvalues) if s_vec[2] != 0: - raise TypeError, "A is assumed to be non-degenerate, but it's det = 0." + raise TypeError("A is assumed to be non-degenerate, but it's det = 0.") ## Return the pair (p,n) return s_vec[:2] @@ -702,7 +702,7 @@ def split_odd(A): if even: print "B:" print B - raise RuntimeError, "The matrix A does not admit a non-even splitting." + raise RuntimeError("The matrix A does not admit a non-even splitting.") return u, B @@ -1383,7 +1383,7 @@ def trains(self): """ ## Check that p = 2 if self._prime != 2: - raise TypeError, "trains() only makes sense when the prime of the p_adic_Genus_Symbol is p=2" + raise TypeError("trains() only makes sense when the prime of the p_adic_Genus_Symbol is p=2") symbol = self._symbol compartments = canonical_2_adic_compartments(symbol) return canonical_2_adic_trains(symbol, compartments) @@ -1415,7 +1415,7 @@ def compartments(self): """ ## Check that p = 2 if self._prime != 2: - raise TypeError, "compartments() only makes sense when the prime of the p_adic_Genus_Symbol is p=2" + raise TypeError("compartments() only makes sense when the prime of the p_adic_Genus_Symbol is p=2") symbol = self._symbol return canonical_2_adic_compartments(symbol) diff --git a/src/sage/quadratic_forms/qfsolve.py b/src/sage/quadratic_forms/qfsolve.py index 0cc719d3fed..558357d4742 100644 --- a/src/sage/quadratic_forms/qfsolve.py +++ b/src/sage/quadratic_forms/qfsolve.py @@ -90,7 +90,7 @@ def qfsolve(G, factD=None): """ gp = _gp_for_simon() if factD is not None: - raise NotImplementedError, "qfsolve not implemented with parameter factD" + raise NotImplementedError("qfsolve not implemented with parameter factD") ret = gp('qfsolve(%s)' % G._pari_init_()) if str(ret.type()) == 't_COL': # Need explicit str(), see #15522 return tuple(QQ(r) for r in ret) diff --git a/src/sage/quadratic_forms/quadratic_form.py b/src/sage/quadratic_forms/quadratic_form.py index a85824c16a6..632c8dbe6df 100644 --- a/src/sage/quadratic_forms/quadratic_form.py +++ b/src/sage/quadratic_forms/quadratic_form.py @@ -386,7 +386,7 @@ def __init__(self, R, n=None, entries=None, unsafe_initialization=False, number_ if is_Matrix(n): ## Test if n is symmetric and has even diagonal if not self._is_even_symmetric_matrix_(n, R): - raise TypeError, "Oops! The matrix is not a symmetric with even diagonal defined over R." + raise TypeError("Oops! The matrix is not a symmetric with even diagonal defined over R.") ## Rename the matrix and ring M = n @@ -399,7 +399,7 @@ def __init__(self, R, n=None, entries=None, unsafe_initialization=False, number_ ## Test if R is symmetric and has even diagonal if not self._is_even_symmetric_matrix_(R): - raise TypeError, "Oops! The matrix is not a symmetric with even diagonal." + raise TypeError("Oops! The matrix is not a symmetric with even diagonal.") ## Rename the matrix and ring M = R @@ -426,9 +426,9 @@ def __init__(self, R, n=None, entries=None, unsafe_initialization=False, number_ try: n = int(n) except Exception: - raise TypeError, "Oops! The size " + str(n) + " must be an integer." + raise TypeError("Oops! The size " + str(n) + " must be an integer.") if (n < 0): - raise TypeError, "Oops! The size " + str(n) + " must be a non-negative integer." + raise TypeError("Oops! The size " + str(n) + " must be a non-negative integer.") ## TODO: Verify that R is a ring... @@ -443,7 +443,7 @@ def __init__(self, R, n=None, entries=None, unsafe_initialization=False, number_ for i in range(N): self.__coeffs[i] = self.__base_ring(entries[i]) elif (entries != None): - raise TypeError, "Oops! The entries " + str(entries) + "must be a list of size n(n+1)/2." + raise TypeError("Oops! The entries " + str(entries) + "must be a list of size n(n+1)/2.") ## ----------------------------------------------------------- @@ -641,7 +641,7 @@ def __setitem__(self, ij, coeff): try: self.__coeffs[i*self.__n - i*(i-1)/2 + j -i] = self.__base_ring(coeff) except Exception: - raise RuntimeError, "Oops! This coefficient can't be coerced to an element of the base ring for the quadratic form." + raise RuntimeError("Oops! This coefficient can't be coerced to an element of the base ring for the quadratic form.") ###################################### @@ -696,9 +696,9 @@ def __add__(self, right): """ if not isinstance(right, QuadraticForm): - raise TypeError, "Oops! Can't add these objects since they're not both quadratic forms. =(" + raise TypeError("Oops! Can't add these objects since they're not both quadratic forms. =(") elif (self.base_ring() != right.base_ring()): - raise TypeError, "Oops! Can't add these since the quadratic forms don't have the same base rings... =(" + raise TypeError("Oops! Can't add these since the quadratic forms don't have the same base rings... =(") else: Q = QuadraticForm(self.base_ring(), self.dim() + right.dim()) n = self.dim() @@ -741,11 +741,11 @@ def sum_by_coefficients_with(self, right): """ if not isinstance(right, QuadraticForm): - raise TypeError, "Oops! Can't add these objects since they're not both quadratic forms. =(" + raise TypeError("Oops! Can't add these objects since they're not both quadratic forms. =(") elif (self.__n != right.__n): - raise TypeError, "Oops! Can't add these since the quadratic forms don't have the same sizes... =(" + raise TypeError("Oops! Can't add these since the quadratic forms don't have the same sizes... =(") elif (self.__base_ring != right.__base_ring): - raise TypeError, "Oops! Can't add these since the quadratic forms don't have the same base rings... =(" + raise TypeError("Oops! Can't add these since the quadratic forms don't have the same base rings... =(") else: return QuadraticForm(self.__base_ring, self.__n, [self.__coeffs[i] + right.__coeffs[i] for i in range(len(self.__coeffs))]) @@ -868,7 +868,7 @@ def __call__(self, v): if is_Matrix(v): ## Check that v has the correct number of rows if v.nrows() != n: - raise TypeError, "Oops! The matrix must have " + str(n) + " rows. =(" + raise TypeError("Oops! The matrix must have " + str(n) + " rows. =(") ## Create the new quadratic form m = v.ncols() @@ -878,20 +878,20 @@ def __call__(self, v): elif (is_Vector(v) or isinstance(v, (list, tuple))): ## Check the vector/tuple/list has the correct length if not (len(v) == n): - raise TypeError, "Oops! Your vector needs to have length " + str(n) + " ." + raise TypeError("Oops! Your vector needs to have length " + str(n) + " .") ## TO DO: Check that the elements can be coerced into the base ring of Q -- on first elt. if len(v) > 0: try: x = self.base_ring()(v[0]) except Exception: - raise TypeError, "Oops! Your vector is not coercible to the base ring of the quadratic form... =(" + raise TypeError("Oops! Your vector is not coercible to the base ring of the quadratic form... =(") ## Attempt to evaluate Q[v] return QFEvaluateVector(self, v) else: - raise(TypeError, "Oops! Presently we can only evaluate a quadratic form on a list, tuple, vector or matrix.") + raise TypeError @@ -922,7 +922,7 @@ def _is_even_symmetric_matrix_(self, A, R=None): """ if not is_Matrix(A): - raise TypeError, "A is not a matrix." + raise TypeError("A is not a matrix.") ring_coerce_test = True if R == None: ## This allows us to omit the ring from the variables, and take it from the matrix @@ -930,7 +930,7 @@ def _is_even_symmetric_matrix_(self, A, R=None): ring_coerce_test = False if not isinstance(R, Ring): - raise TypeError, "R is not a ring." + raise TypeError("R is not a ring.") if not A.is_square(): return False @@ -1070,7 +1070,7 @@ def Gram_matrix(self): if Int_flag: return MatrixSpace(self.base_ring(), n, n)(A) else: - raise TypeError, "Oops! This form does not have an integral Gram matrix. =(" + raise TypeError("Oops! This form does not have an integral Gram matrix. =(") def has_integral_Gram_matrix(self): @@ -1124,7 +1124,7 @@ def gcd(self): 2 """ if self.base_ring() != ZZ: - raise TypeError, "Oops! The given quadratic form must be defined over ZZ." + raise TypeError("Oops! The given quadratic form must be defined over ZZ.") return GCD(self.coefficients()) @@ -1173,7 +1173,7 @@ def polynomial(self,names='x'): try: R = PolynomialRing(self.base_ring(),names,n) except Exception: - raise ValueError, 'Can only create polynomial rings over commutative rings.' + raise ValueError('Can only create polynomial rings over commutative rings.') V = vector(R.gens()) P = (V*M).dot_product(V) return P @@ -1219,7 +1219,7 @@ def primitive(self): """ if self.base_ring() != ZZ: - raise TypeError, "Oops! The given quadratic form must be defined over ZZ." + raise TypeError("Oops! The given quadratic form must be defined over ZZ.") g = self.gcd() return QuadraticForm(self.base_ring(), self.dim(), [ZZ(x/g) for x in self.coefficients()]) @@ -1374,9 +1374,9 @@ def base_change_to(self, R): """ ## Check that a canonical coercion is possible if not is_Ring(R): - raise TypeError, "Oops! R is not a ring. =(" + raise TypeError("Oops! R is not a ring. =(") if not R.has_coerce_map_from(self.base_ring()): - raise TypeError, "Oops! There is no canonical coercion from " + str(self.base_ring()) + " to R." + raise TypeError("Oops! There is no canonical coercion from " + str(self.base_ring()) + " to R.") ## Return the coerced form return QuadraticForm(R, self.dim(), [R(x) for x in self.coefficients()]) @@ -1415,7 +1415,7 @@ def level(self): ## Check that the base ring is a PID if not is_PrincipalIdealDomain(self.base_ring()): - raise TypeError, "Oops! The level (as a number) is only defined over a Principal Ideal Domain. Try using level_ideal()." + raise TypeError("Oops! The level (as a number) is only defined over a Principal Ideal Domain. Try using level_ideal().") ## Warn the user if the form is defined over a field! @@ -1428,7 +1428,7 @@ def level(self): try: mat_inv = self.matrix()**(-1) except ZeroDivisionError: - raise TypeError, "Oops! The quadratic form is degenerate (i.e. det = 0). =(" + raise TypeError("Oops! The quadratic form is degenerate (i.e. det = 0). =(") ## Compute the level inv_denoms = [] diff --git a/src/sage/quadratic_forms/quadratic_form__automorphisms.py b/src/sage/quadratic_forms/quadratic_form__automorphisms.py index 10b0b77f6a8..680df6ef9e2 100644 --- a/src/sage/quadratic_forms/quadratic_form__automorphisms.py +++ b/src/sage/quadratic_forms/quadratic_form__automorphisms.py @@ -357,7 +357,7 @@ def automorphisms(self): """ ## only for definite forms if not self.is_definite(): - raise ValueError, "not a definite form in QuadraticForm.automorphisms()" + raise ValueError("not a definite form in QuadraticForm.automorphisms()") ## Check for a cached value try: @@ -456,7 +456,7 @@ def number_of_automorphisms(self, recompute=False): """ ## only for definite forms if not self.is_definite(): - raise ValueError, "not a definite form in QuadraticForm.number_of_automorphisms()" + raise ValueError("not a definite form in QuadraticForm.number_of_automorphisms()") ## Try to use the cached version if we can if not recompute: @@ -530,7 +530,7 @@ def number_of_automorphisms__souvigner(self): return num_of_autos ## Raise and error if we're here: - raise RuntimeError, "Oops! There is a problem..." + raise RuntimeError("Oops! There is a problem...") diff --git a/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py b/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py index 5ffa3909509..cf01eb2f177 100644 --- a/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py +++ b/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py @@ -88,7 +88,7 @@ def is_globally_equivalent__souvigner(self, other, return_transformation=False): G2 = open(G1.name, 'r') line = G2.readline() if line.startswith("Error:"): - raise RuntimeError, "There is a problem using the souvigner code... " + line + raise RuntimeError("There is a problem using the souvigner code... " + line) elif line.find("not isomorphic") != -1: ## Checking if this text appears, if so then they're not isomorphic! return False else: @@ -120,7 +120,7 @@ def is_globally_equivalent__souvigner(self, other, return_transformation=False): #return True, M ## Raise and error if we're here: - raise RuntimeError, "Oops! There is a problem..." + raise RuntimeError("Oops! There is a problem...") @@ -174,12 +174,12 @@ def is_globally_equivalent_to(self, other, return_matrix=False, check_theta_to_p """ ## only for definite forms if not self.is_definite(): - raise ValueError, "not a definite form in QuadraticForm.is_globally_equivalent_to()" + raise ValueError("not a definite form in QuadraticForm.is_globally_equivalent_to()") ## Check that other is a QuadraticForm #if not isinstance(other, QuadraticForm): if not is_QuadraticForm(other): - raise TypeError, "Oops! You must compare two quadratic forms, but the argument is not a quadratic form. =(" + raise TypeError("Oops! You must compare two quadratic forms, but the argument is not a quadratic form. =(") ## Now use the Souvigner code by default! =) @@ -262,7 +262,7 @@ def is_locally_equivalent_to(self, other, check_primes_only=False, force_jordan_ """ ## TO IMPLEMENT: if self.det() == 0: - raise NotImplementedError, "OOps! We need to think about whether this still works for degenerate forms... especially check the signature." + raise NotImplementedError("OOps! We need to think about whether this still works for degenerate forms... especially check the signature.") ## Check that both forms have the same dimension and base ring if (self.dim() != other.dim()) or (self.base_ring() != other.base_ring()): @@ -332,9 +332,9 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): ## Sanity Checks #if not isinstance(other, QuadraticForm): if type(other) != type(self): - raise TypeError, "Oops! The first argument must be of type QuadraticForm." + raise TypeError("Oops! The first argument must be of type QuadraticForm.") if not is_prime(p): - raise TypeError, "Oops! The second argument must be a prime number." + raise TypeError("Oops! The second argument must be a prime number.") ## Get the relevant local normal forms quickly self_jordan = self.jordan_blocks_by_scale_and_unimodular(p, safe_flag= False) @@ -411,7 +411,7 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): ## SANITY CHECK -- check that the scale powers are strictly increasing for i in range(1, len(scale_list)): if scale_list[i-1] >= scale_list[i]: - raise RuntimeError, "Oops! There is something wrong with the Jordan Decomposition -- the given scales are not strictly increasing!" + raise RuntimeError("Oops! There is something wrong with the Jordan Decomposition -- the given scales are not strictly increasing!") ## DIAGNOSTIC @@ -448,7 +448,7 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): return True else: - raise TypeError, "Oops! This should not have happened." + raise TypeError("Oops! This should not have happened.") diff --git a/src/sage/quadratic_forms/quadratic_form__genus.py b/src/sage/quadratic_forms/quadratic_form__genus.py index 2caf2f9a325..6c1343efd0d 100644 --- a/src/sage/quadratic_forms/quadratic_form__genus.py +++ b/src/sage/quadratic_forms/quadratic_form__genus.py @@ -55,13 +55,13 @@ def global_genus_symbol(self): """ ## Check that the form is defined over ZZ if not self.base_ring() == IntegerRing(): - raise TypeError, "Oops! The quadratic form is not defined over the integers." + raise TypeError("Oops! The quadratic form is not defined over the integers.") ## Return the result try: return Genus(self.Hessian_matrix()) except Exception: - raise TypeError, "Oops! There is a problem computing the genus symbols for this form." + raise TypeError("Oops! There is a problem computing the genus symbols for this form.") @@ -119,16 +119,16 @@ def local_genus_symbol(self, p): """ ## Check that p is prime and that the form is defined over ZZ. if not is_prime(p): - raise TypeError, "Oops! The number " + str(p) + " isn't prime." + raise TypeError("Oops! The number " + str(p) + " isn't prime.") if not self.base_ring() == IntegerRing(): - raise TypeError, "Oops! The quadratic form is not defined over the integers." + raise TypeError("Oops! The quadratic form is not defined over the integers.") ## Return the result try: M = self.Hessian_matrix() return LocalGenusSymbol(M, p) except Exception: - raise TypeError, "Oops! There is a problem computing the local genus symbol at the prime " + str(p) + " for this form." + raise TypeError("Oops! There is a problem computing the local genus symbol at the prime " + str(p) + " for this form.") diff --git a/src/sage/quadratic_forms/quadratic_form__local_density_congruence.py b/src/sage/quadratic_forms/quadratic_form__local_density_congruence.py index 05fe7376854..9262eb9f6e2 100644 --- a/src/sage/quadratic_forms/quadratic_form__local_density_congruence.py +++ b/src/sage/quadratic_forms/quadratic_form__local_density_congruence.py @@ -115,9 +115,9 @@ def local_good_density_congruence_odd(self, p, m, Zvec, NZvec): ## ------------------------------- Sn = Set(range(n)) if (Zvec != None) and (len(Set(Zvec) + Sn) > n): - raise RuntimeError, "Zvec must be a subset of {0, ..., n-1}." + raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.") if (NZvec != None) and (len(Set(NZvec) + Sn) > n): - raise RuntimeError, "NZvec must be a subset of {0, ..., n-1}." + raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.") @@ -250,9 +250,9 @@ def local_good_density_congruence_even(self, m, Zvec, NZvec): ## ------------------------------- Sn = Set(range(n)) if (Zvec != None) and (len(Set(Zvec) + Sn) > n): - raise RuntimeError, "Zvec must be a subset of {0, ..., n-1}." + raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.") if (NZvec != None) and (len(Set(NZvec) + Sn) > n): - raise RuntimeError, "NZvec must be a subset of {0, ..., n-1}." + raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.") @@ -410,9 +410,9 @@ def local_good_density_congruence(self, p, m, Zvec=None, NZvec=None): ## ------------------------------- Sn = Set(range(n)) if (Zvec != None) and (len(Set(Zvec) + Sn) > n): - raise RuntimeError, "Zvec must be a subset of {0, ..., n-1}." + raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.") if (NZvec != None) and (len(Set(NZvec) + Sn) > n): - raise RuntimeError, "NZvec must be a subset of {0, ..., n-1}." + raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.") @@ -434,7 +434,7 @@ def local_good_density_congruence(self, p, m, Zvec=None, NZvec=None): #print "\n Using the (p=2) Local_Good_Density_Even routine! \n" return self.local_good_density_congruence_even(m, Zvec, NZvec) - raise RuntimeError, "\n Error in Local_Good_Density: The 'prime' p = " + str(p) + " is < 2. \n" + raise RuntimeError("\n Error in Local_Good_Density: The 'prime' p = " + str(p) + " is < 2. \n") @@ -504,9 +504,9 @@ def local_zero_density_congruence(self, p, m, Zvec=None, NZvec=None): ## ------------------------------- Sn = Set(range(n)) if (Zvec != None) and (len(Set(Zvec) + Sn) > n): - raise RuntimeError, "Zvec must be a subset of {0, ..., n-1}." + raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.") if (NZvec != None) and (len(Set(NZvec) + Sn) > n): - raise RuntimeError, "NZvec must be a subset of {0, ..., n-1}." + raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.") p2 = p * p @@ -611,9 +611,9 @@ def local_badI_density_congruence(self, p, m, Zvec=None, NZvec=None): ## ------------------------------- Sn = Set(range(n)) if (Zvec != None) and (len(Set(Zvec) + Sn) > n): - raise RuntimeError, "Zvec must be a subset of {0, ..., n-1}." + raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.") if (NZvec != None) and (len(Set(NZvec) + Sn) > n): - raise RuntimeError, "NZvec must be a subset of {0, ..., n-1}." + raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.") @@ -662,7 +662,7 @@ def local_badI_density_congruence(self, p, m, Zvec=None, NZvec=None): if (S0 == []): print " Using Q = " + str(self) print " and p = " + str(p) - raise RuntimeError, "Oops! The form is not primitive!" + raise RuntimeError("Oops! The form is not primitive!") @@ -784,9 +784,9 @@ def local_badII_density_congruence(self, p, m, Zvec=None, NZvec=None): ## ------------------------------- Sn = Set(range(n)) if (Zvec != None) and (len(Set(Zvec) + Sn) > n): - raise RuntimeError, "Zvec must be a subset of {0, ..., n-1}." + raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.") if (NZvec != None) and (len(Set(NZvec) + Sn) > n): - raise RuntimeError, "NZvec must be a subset of {0, ..., n-1}." + raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.") ## Define the indexing sets S_i: @@ -836,7 +836,7 @@ def local_badII_density_congruence(self, p, m, Zvec=None, NZvec=None): if (S0 == []): print " Using Q = " + str(self) print " and p = " + str(p) - raise RuntimeError, "Oops! The form is not primitive!" + raise RuntimeError("Oops! The form is not primitive!") diff --git a/src/sage/quadratic_forms/quadratic_form__local_density_interfaces.py b/src/sage/quadratic_forms/quadratic_form__local_density_interfaces.py index 72da0ab2e1f..2afb1b26a2c 100644 --- a/src/sage/quadratic_forms/quadratic_form__local_density_interfaces.py +++ b/src/sage/quadratic_forms/quadratic_form__local_density_interfaces.py @@ -44,7 +44,7 @@ def local_density(self, p, m): """ n = self.dim() if (n == 0): - raise TypeError, "Oops! We currently don't handle 0-dim'l forms. =(" + raise TypeError("Oops! We currently don't handle 0-dim'l forms. =(") ## Find the local normal form and p-scale of Q -- Note: This uses the valuation ordering of local_normal_form. ## TO DO: Write a separate p-scale and p-norm routines! @@ -120,7 +120,7 @@ def local_primitive_density(self, p, m): """ n = self.dim() if (n == 0): - raise TypeError, "Oops! We currently don't handle 0-dim'l forms. =(" + raise TypeError("Oops! We currently don't handle 0-dim'l forms. =(") ## Find the local normal form and p-scale of Q -- Note: This uses the valuation ordering of local_normal_form. ## TO DO: Write a separate p-scale and p-norm routines! diff --git a/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py b/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py index 7531cfb8674..30d03fc60a8 100644 --- a/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py +++ b/src/sage/quadratic_forms/quadratic_form__local_field_invariants.py @@ -518,7 +518,7 @@ def is_anisotropic(self, p): if (n == 1): return (self[0,0] != 0) - raise NotImplementedError, "Oops! We haven't established a convention for 0-dim'l quadratic forms... =(" + raise NotImplementedError("Oops! We haven't established a convention for 0-dim'l quadratic forms... =(") def is_isotropic(self, p): @@ -677,7 +677,7 @@ def compute_definiteness(self): """ ## Sanity Check if not ((self.base_ring() == ZZ) or (self.base_ring() == QQ) or (self.base_ring() == RR)): - raise NotImplementedError, "Oops! We can only check definiteness over ZZ, QQ, and RR for now." + raise NotImplementedError("Oops! We can only check definiteness over ZZ, QQ, and RR for now.") ## Some useful variables n = self.dim() @@ -752,7 +752,7 @@ def compute_definiteness_string_by_determinants(self): """ ## Sanity Check if not ((self.base_ring() == ZZ) or (self.base_ring() == QQ) or (self.base_ring() == RR)): - raise NotImplementedError, "Oops! We can only check definiteness over ZZ, QQ, and RR for now." + raise NotImplementedError("Oops! We can only check definiteness over ZZ, QQ, and RR for now.") ## Some useful variables n = self.dim() diff --git a/src/sage/quadratic_forms/quadratic_form__local_normal_form.py b/src/sage/quadratic_forms/quadratic_form__local_normal_form.py index 2d01f704c0d..e6a19751f11 100644 --- a/src/sage/quadratic_forms/quadratic_form__local_normal_form.py +++ b/src/sage/quadratic_forms/quadratic_form__local_normal_form.py @@ -123,9 +123,9 @@ def local_normal_form(self, p): """ ## Sanity Checks if (self.base_ring() != IntegerRing()): - raise NotImplementedError, "Oops! This currently only works for quadratic forms defined over IntegerRing(). =(" + raise NotImplementedError("Oops! This currently only works for quadratic forms defined over IntegerRing(). =(") if not ((p>=2) and is_prime(p)): - raise TypeError, "Oops! p is not a positive prime number. =(" + raise TypeError("Oops! p is not a positive prime number. =(") ## Some useful local variables Q = copy.deepcopy(self) @@ -149,7 +149,7 @@ def local_normal_form(self, p): ## Error if we still haven't seen non-zero coefficients! if (min_val == Infinity): - raise RuntimeError, "Oops! The original matrix is degenerate. =(" + raise RuntimeError("Oops! The original matrix is degenerate. =(") ## Step 2: Arrange for the upper leftmost entry to have minimal valuation @@ -208,7 +208,7 @@ def local_normal_form(self, p): ## Sanity Check: a/g is a p-unit if valuation (g, p) != valuation(a, p): - raise RuntimeError, "Oops! We have a problem with our rescaling not preserving p-integrality!" + raise RuntimeError("Oops! We have a problem with our rescaling not preserving p-integrality!") Q.multiply_variable(ZZ(a/g), j, in_place = True) ## Ensures that the new b entry is divisible by a Q.add_symmetric(ZZ(-b/g), j, 0, in_place = True) ## Performs the cancellation @@ -260,14 +260,14 @@ def local_normal_form(self, p): Q[1, 1] = min_scale Q[0, 1] = min_scale else: - raise RuntimeError, "Error in LocalNormal: Impossible behavior for a 2x2 block! \n" + raise RuntimeError("Error in LocalNormal: Impossible behavior for a 2x2 block! \n") ## Check that the cancellation worked, extract the upper-left block, and trim Q to handle the next block. for i in range(block_size): for j in range(block_size, n): if Q[i,j] != 0: - raise RuntimeError, "Oops! The cancellation didn't work properly at entry (" + str(i) + ", " + str(j) + ")." + raise RuntimeError("Oops! The cancellation didn't work properly at entry (" + str(i) + ", " + str(j) + ").") Q_Jordan = Q_Jordan + Q.extract_variables(range(block_size)) Q = Q.extract_variables(range(block_size, n)) @@ -442,7 +442,7 @@ def jordan_blocks_in_unimodular_list_by_scale_power(self, p): """ ## Sanity Check if self.base_ring() != ZZ: - raise TypeError, "Oops! This method only makes sense for integer-valued quadratic forms (i.e. defined over ZZ)." + raise TypeError("Oops! This method only makes sense for integer-valued quadratic forms (i.e. defined over ZZ).") ## Deal with zero dim'l forms if self.dim() == 0: @@ -453,8 +453,8 @@ def jordan_blocks_in_unimodular_list_by_scale_power(self, p): scale_list = [P[0] for P in list_of_jordan_pairs] s_max = max(scale_list) if min(scale_list) < 0: - raise TypeError, "Oops! The given quadratic form has a Jordan component with a negative scale exponent!\n" \ - + "This routine requires an integer-matrix quadratic form for the output indexing to work properly!" + raise TypeError("Oops! The given quadratic form has a Jordan component with a negative scale exponent!\n" \ + + "This routine requires an integer-matrix quadratic form for the output indexing to work properly!") ## Make the new list of unimodular Jordan components zero_form = copy.deepcopy(self) diff --git a/src/sage/quadratic_forms/quadratic_form__local_representation_conditions.py b/src/sage/quadratic_forms/quadratic_form__local_representation_conditions.py index fa4ef8149ed..9b77e984dc4 100644 --- a/src/sage/quadratic_forms/quadratic_form__local_representation_conditions.py +++ b/src/sage/quadratic_forms/quadratic_form__local_representation_conditions.py @@ -121,7 +121,7 @@ def __init__(self, Q): ## Check that the form Q is integer-valued (we can relax this later) if Q.base_ring() != ZZ: - raise TypeError, "We require that the quadratic form be defined over ZZ (integer-values) for now." + raise TypeError("We require that the quadratic form be defined over ZZ (integer-values) for now.") ## Basic structure initialization @@ -383,7 +383,7 @@ def local_conditions_vector_for_prime(self, p): else: return [p, infinity, infinity, infinity, infinity, None, None, None, None] - raise RuntimeError, "Error... The dimension stored should be a non-negative integer!" + raise RuntimeError("Error... The dimension stored should be a non-negative integer!") @@ -422,7 +422,7 @@ def is_universal_at_prime(self, p): if p == infinity: v = self.local_repn_array[0] if p != v[0]: - raise RuntimeError, "Error... The first vector should be for the real numbers!" + raise RuntimeError("Error... The first vector should be for the real numbers!") return (v[1:3] == [0,0]) ## True iff the form is indefinite ## Check non-generic "finite" primes @@ -555,7 +555,7 @@ def is_locally_represented_at_place(self, m, p): """ ## Sanity Check if not m in QQ: - raise TypeError, "Oops! m = " + str(m) + " is not a rational number!" + raise TypeError("Oops! m = " + str(m) + " is not a rational number!") ## Representing zero if m == 0: diff --git a/src/sage/quadratic_forms/quadratic_form__mass__Conway_Sloane_masses.py b/src/sage/quadratic_forms/quadratic_form__mass__Conway_Sloane_masses.py index 446f351fdb5..4ca292176d4 100644 --- a/src/sage/quadratic_forms/quadratic_form__mass__Conway_Sloane_masses.py +++ b/src/sage/quadratic_forms/quadratic_form__mass__Conway_Sloane_masses.py @@ -88,7 +88,7 @@ def parity(self, allow_rescaling_flag=True): ind = scale_pow_list.index(min_scale_pow) else: if min_scale_pow < 0: - raise TypeError, "Oops! If rescaling is not allowed, then we require our form to have an integral Gram matrix." + raise TypeError("Oops! If rescaling is not allowed, then we require our form to have an integral Gram matrix.") ind = scale_pow_list.index(0) @@ -188,7 +188,7 @@ def conway_species_list_at_odd_prime(self, p): """ ## Sanity Check: if not ((p>2) and is_prime(p)): - raise TypeError, "Oops! We are assuming that p is an odd positive prime number." + raise TypeError("Oops! We are assuming that p is an odd positive prime number.") ## Deal with the zero-dim'l form if self.dim() == 0: @@ -364,7 +364,7 @@ def conway_octane_of_this_unimodular_Jordan_block_at_2(self): else: B = self[ind, ind+1] if (B % 2 != 0): - raise RuntimeError, "Oops, we expected the mixed term to be even! " + raise RuntimeError("Oops, we expected the mixed term to be even! ") a = self[ind, ind] b = ZZ(B / ZZ(2)) @@ -383,7 +383,7 @@ def conway_octane_of_this_unimodular_Jordan_block_at_2(self): ind += 2 u = tmp_diag_vec[0] else: - raise RuntimeError, "Oops! This should not happen -- the odd 2x2 blocks have disc 1 or 5 (mod 8)." + raise RuntimeError("Oops! This should not happen -- the odd 2x2 blocks have disc 1 or 5 (mod 8).") ## Compute the octane octane = 0 @@ -393,7 +393,7 @@ def conway_octane_of_this_unimodular_Jordan_block_at_2(self): elif a % 4 == 3: octane += -1 else: - raise RuntimeError, "Oops! The diagonal elements should all be odd... =(" + raise RuntimeError("Oops! The diagonal elements should all be odd... =(") ## Return its value return octane % 8 diff --git a/src/sage/quadratic_forms/quadratic_form__mass__Siegel_densities.py b/src/sage/quadratic_forms/quadratic_form__mass__Siegel_densities.py index fd451e0d225..acf9a554b26 100644 --- a/src/sage/quadratic_forms/quadratic_form__mass__Siegel_densities.py +++ b/src/sage/quadratic_forms/quadratic_form__mass__Siegel_densities.py @@ -108,12 +108,12 @@ def mass__by_Siegel_densities(self, odd_algorithm="Pall", even_algorithm="Watson elif even_algorithm == "Watson": p_adjustment = p_adjustment / self.Watson_mass_at_2() else: - raise TypeError, "There is a problem -- your even_algorithm argument is invalid. Try again. =(" + raise TypeError("There is a problem -- your even_algorithm argument is invalid. Try again. =(") else: if odd_algorithm == "Pall": p_adjustment = p_adjustment / self.Pall_mass_density_at_odd_prime(p) else: - raise TypeError, "There is a problem -- your optional arguments are invalid. Try again. =(" + raise TypeError("There is a problem -- your optional arguments are invalid. Try again. =(") #print "p_adjustment for p =", p, "is", p_adjustment @@ -160,7 +160,7 @@ def Pall_mass_density_at_odd_prime(self, p): """ ## Check that p is a positive prime -- unnecessary since it's done implicitly in the next step. =) if p<=2: - raise TypeError, "Oops! We need p to be a prime > 2." + raise TypeError("Oops! We need p to be a prime > 2.") ## Step 1: Obtain a p-adic (diagonal) local normal form, and ## compute the invariants for each Jordan block. diff --git a/src/sage/quadratic_forms/quadratic_form__neighbors.py b/src/sage/quadratic_forms/quadratic_form__neighbors.py index 720246a3f18..c5cefdce612 100644 --- a/src/sage/quadratic_forms/quadratic_form__neighbors.py +++ b/src/sage/quadratic_forms/quadratic_form__neighbors.py @@ -105,7 +105,7 @@ def find_primitive_p_divisible_vector__next(self, p, v=None): ## Handle n = 1 separately. if n <= 1: - raise RuntimeError, "Sorry -- Not implemented yet!" + raise RuntimeError("Sorry -- Not implemented yet!") ## Look for the last non-zero entry (which must be 1) @@ -189,7 +189,7 @@ def find_p_neighbor_from_vec(self, p, v): while ((y_ind < n) and (v_dual[y_ind] % p) == 0): ## Check the dot product for the std basis vectors! y_ind += 1 if y_ind == n: - raise RuntimeError, "Oops! One of the standard basis vectors should have worked." + raise RuntimeError("Oops! One of the standard basis vectors should have worked.") w = vector([R(i == y_ind) for i in range(n)]) vw_prod = (v * self.matrix()).dot_product(w) diff --git a/src/sage/quadratic_forms/quadratic_form__reduction_theory.py b/src/sage/quadratic_forms/quadratic_form__reduction_theory.py index 50fe77764af..32e89714ecf 100644 --- a/src/sage/quadratic_forms/quadratic_form__reduction_theory.py +++ b/src/sage/quadratic_forms/quadratic_form__reduction_theory.py @@ -28,7 +28,7 @@ def reduced_binary_form1(self): ) """ if self.dim() != 2: - raise TypeError, "This must be a binary form for now..." + raise TypeError("This must be a binary form for now...") R = self.base_ring() interior_reduced_flag = False @@ -74,7 +74,7 @@ def reduced_ternary_form__Dickson(self): NotImplementedError: TO DO """ - raise NotImplementedError, "TO DO" + raise NotImplementedError("TO DO") @@ -294,8 +294,8 @@ def minkowski_reduction_for_4vars__SP(self): ## Only allow 4-variable forms if n != 4: - raise TypeError, "Oops! The given quadratic form has " + str(n) + \ - " != 4 variables. =|" + raise TypeError("Oops! The given quadratic form has " + str(n) + \ + " != 4 variables. =|") ## Step 1: Begin the reduction diff --git a/src/sage/quadratic_forms/quadratic_form__split_local_covering.py b/src/sage/quadratic_forms/quadratic_form__split_local_covering.py index 8d5d4f3669f..10fb7f68e04 100644 --- a/src/sage/quadratic_forms/quadratic_form__split_local_covering.py +++ b/src/sage/quadratic_forms/quadratic_form__split_local_covering.py @@ -83,7 +83,7 @@ def cholesky_decomposition(self, bit_prec = 53): ## Check that the precision passed is allowed. if isinstance(self.base_ring(), RealField_class) and (self.base_ring().prec() < bit_prec): - raise RuntimeError, "Oops! The precision requested is greater than that of the given quadratic form!" + raise RuntimeError("Oops! The precision requested is greater than that of the given quadratic form!") ## 1. Initialization n = self.dim() @@ -255,7 +255,7 @@ def vectors_by_length(self, bound): if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val - raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." + raise RuntimeError("The roundoff error is bigger than 0.001, so we should use more precision somewhere...") #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double @@ -346,7 +346,7 @@ def complementary_subform_to_vector(self, v): ## Abort if v is the zero vector if nz == n: - raise TypeError, "Oops, v cannot be the zero vector! =(" + raise TypeError("Oops, v cannot be the zero vector! =(") ## Make the change of basis matrix new_basis = extend_to_primitive(matrix(ZZ,n,1,v)) @@ -383,7 +383,7 @@ def complementary_subform_to_vector(self, v): done_flag = False if done_flag == False: - raise RuntimeError, "There is a problem cancelling out the matrix entries! =O" + raise RuntimeError("There is a problem cancelling out the matrix entries! =O") ## Return the complementary matrix diff --git a/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py b/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py index 55820aa7d02..57b529bd684 100644 --- a/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py +++ b/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py @@ -167,7 +167,7 @@ def antiadjoint(self): else: return self.adjoint().scale_by_factor( R(1) / d**(n-2) ) except TypeError: - raise ValueError, "not an adjoint" + raise ValueError("not an adjoint") def is_adjoint(self): @@ -454,7 +454,7 @@ def basiclemmavec(self,M): if M0 == 1: return __crt_list(vec,mod) - raise ValueError, "not primitive form" + raise ValueError("not primitive form") ### FIXME: get the rules for validity of characters straight... @@ -479,9 +479,9 @@ def xi(self,p): """ if self.dim() == 2 and self.disc() % p: - raise ValueError, "not a valid character" + raise ValueError("not a valid character") if self.dim() >= 3 and self.omega() % p: - raise ValueError, "not a valid character" + raise ValueError("not a valid character") if (p == -1) or (p == 2): return kronecker_symbol(p, self.basiclemma(2)) return kronecker_symbol(self.basiclemma(p), p) diff --git a/src/sage/quadratic_forms/quadratic_form__theta.py b/src/sage/quadratic_forms/quadratic_form__theta.py index 3f40f9a9195..1030423a322 100644 --- a/src/sage/quadratic_forms/quadratic_form__theta.py +++ b/src/sage/quadratic_forms/quadratic_form__theta.py @@ -64,10 +64,10 @@ def theta_series(self, Max=10, var_str='q', safe_flag=True): if (Max not in ['mod_form']) and (not M >= 0): print Max - raise TypeError, "Oops! Max is not an integer >= 0 or an allowed string." + raise TypeError("Oops! Max is not an integer >= 0 or an allowed string.") if Max == 'mod_form': - raise NotImplementedError, "Oops! We have to figure out the correct number of Fourier coefficients to use..." + raise NotImplementedError("Oops! We have to figure out the correct number of Fourier coefficients to use...") #return self.theta_by_pari(sturm_bound(self.level(), self.dim() / ZZ(2)) + 1, var_str, safe_flag) else: return self.theta_by_pari(M, var_str, safe_flag) @@ -295,10 +295,10 @@ def theta_by_cholesky(self, q_prec): ## OPTIONAL SAFETY CHECK: eps = 0.000000001 if (abs(Q_val_double - Q_val) > eps): - raise RuntimeError, "Oh No! We have a problem with the floating point precision... \n" \ + raise RuntimeError("Oh No! We have a problem with the floating point precision... \n" \ + " Q_val_double = " + str(Q_val_double) + "\n" \ + " Q_val = " + str(Q_val) + "\n" \ - + " x = " + str(x) + "\n" + + " x = " + str(x) + "\n") ## DIAGNOSTIC @@ -364,16 +364,16 @@ def theta_series_degree_2(Q, prec): (preprint) """ if Q.base_ring() != ZZ: - raise TypeError, "The quadratic form must be integral" + raise TypeError("The quadratic form must be integral") if not Q.is_positive_definite(): - raise ValueError, "The quadratic form must be positive definite" + raise ValueError("The quadratic form must be positive definite") try: X = ZZ(prec-1) # maximum discriminant except TypeError: - raise TypeError, "prec is not an integer" + raise TypeError("prec is not an integer") if X < -1: - raise ValueError, "prec must be >= 0" + raise ValueError("prec must be >= 0") if X == -1: return {} diff --git a/src/sage/quadratic_forms/quadratic_form__variable_substitutions.py b/src/sage/quadratic_forms/quadratic_form__variable_substitutions.py index baa3b8d8c2d..b2bb9957b17 100644 --- a/src/sage/quadratic_forms/quadratic_form__variable_substitutions.py +++ b/src/sage/quadratic_forms/quadratic_form__variable_substitutions.py @@ -214,9 +214,9 @@ def scale_by_factor(self, c, change_value_ring_flag=False): return Q except Exception: if (change_value_ring_flag == False): - raise TypeError, "Oops! We could not rescale the lattice in this way and preserve its defining ring." + raise TypeError("Oops! We could not rescale the lattice in this way and preserve its defining ring.") else: - raise UntestedCode, "This code is not tested by current doctests!" + raise UntestedCode("This code is not tested by current doctests!") F = R.fraction_field() list2 = [F(x) for x in new_coeff_list] Q = copy.deepcopy(self) diff --git a/src/sage/quadratic_forms/random_quadraticform.py b/src/sage/quadratic_forms/random_quadraticform.py index 7c341949d08..19f62cfcf6d 100644 --- a/src/sage/quadratic_forms/random_quadraticform.py +++ b/src/sage/quadratic_forms/random_quadraticform.py @@ -55,9 +55,9 @@ def random_quadraticform(R, n, rand_arg_list=[]): """ ## Sanity Checks: We have a ring and there are at most 3 parameters for randomness! if len(rand_arg_list) > 3: - raise TypeError, "Oops! The list of randomness arguments can have at most 3 elements." + raise TypeError("Oops! The list of randomness arguments can have at most 3 elements.") if not is_Ring(R): - raise TypeError, "Oops! The first argument must be a ring." + raise TypeError("Oops! The first argument must be a ring.") ## Create a list of upper-triangular entries for the quadratic form L = len(rand_arg_list) diff --git a/src/sage/quadratic_forms/ternary_qf.py b/src/sage/quadratic_forms/ternary_qf.py index 9548e646aae..828e86cf1e2 100644 --- a/src/sage/quadratic_forms/ternary_qf.py +++ b/src/sage/quadratic_forms/ternary_qf.py @@ -98,7 +98,7 @@ def __init__(self,v): if len(v) != 6: # Check we have six coefficients - raise ValueError, "Ternary quadratic form must be given by a list of six coefficients" + raise ValueError("Ternary quadratic form must be given by a list of six coefficients") self._a, self._b, self._c, self._r, self._s, self._t = [ZZ(x) for x in v] self._automorphisms = None self._number_of_automorphisms = None @@ -218,7 +218,7 @@ def __call__(self, v): if is_Matrix(v): ## Check that v has 3 rows if v.nrows() != 3: - raise TypeError, "Oops! The matrix must have 3 rows." + raise TypeError("Oops! The matrix must have 3 rows.") ## Check if v has 3 cols if v.ncols() == 3: M = v.transpose() * self.matrix() * v @@ -228,12 +228,12 @@ def __call__(self, v): elif (is_Vector(v) or isinstance(v, (list, tuple))): ## Check that v has lenght 3 if not (len(v) == 3): - raise TypeError, "Oops! Your vector needs to have length 3" + raise TypeError("Oops! Your vector needs to have length 3") v0, v1, v2 = v a, b, c, r, s, t = self.coefficients() return a*v0**2 + b*v1**2 + c*v2**2 + r*v1*v2 + s*v0*v2 + t*v0*v1 else: - raise TypeError, "Oops! Presently we can only evaluate a quadratic form on a list, tuple, vector ot matrix" + raise TypeError("Oops! Presently we can only evaluate a quadratic form on a list, tuple, vector ot matrix") def quadratic_form(self): @@ -539,7 +539,7 @@ def scale_by_factor(self, k): else: - raise TypeError, "Oops! " + k.__repr__() + " doesn't belongs to a Ring" + raise TypeError("Oops! " + k.__repr__() + " doesn't belongs to a Ring") def reciprocal(self): """ @@ -1022,13 +1022,13 @@ def xi(self, p): p = 2 if self.omega() % p != 0: - raise ValueError, "not a valid character" + raise ValueError("not a valid character") if p == -1 and self.omega() % 2**4 != 0: - raise ValueError, "not a valid character" + raise ValueError("not a valid character") if p == 2 and self.omega() % 2**5 != 0: - raise ValueError, "not a valid character" + raise ValueError("not a valid character") if (p == -1) or (p == 2): return kronecker_symbol(p, self.basic_lemma(2)) @@ -1809,7 +1809,7 @@ def automorphisms(self, slow = True): """ if not self.is_definite(): - raise ValueError, "Oops, only implemented for definite forms." + raise ValueError("Oops, only implemented for definite forms.") if self._automorphisms != None: return self._automorphisms @@ -2040,7 +2040,7 @@ def number_of_automorphisms(self, slow = True): """ if not self.is_definite(): - raise ValueError, "Oops, only implemented for definite forms." + raise ValueError("Oops, only implemented for definite forms.") if self._number_of_automorphisms != None: return self._number_of_automorphisms diff --git a/src/sage/rings/arith.py b/src/sage/rings/arith.py index aec9219f2b8..21b6e3d8242 100644 --- a/src/sage/rings/arith.py +++ b/src/sage/rings/arith.py @@ -163,7 +163,7 @@ def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_dig x^2 - 2*x + 5 """ if proof and not height_bound: - raise ValueError, "height_bound must be given for proof=True" + raise ValueError("height_bound must be given for proof=True") x = ZZ['x'].gen() @@ -226,16 +226,16 @@ def norm(v): # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: - raise ValueError, "insufficient precision for non-existence proof" + raise ValueError("insufficient precision for non-existence proof") return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): - raise ValueError, "insufficient precision for uniqueness proof" + raise ValueError("insufficient precision for uniqueness proof") if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: - raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" + raise NotImplementedError("proof and height bound only implemented for real and complex numbers") else: y = pari(z) @@ -331,7 +331,7 @@ def bernoulli(n, algorithm='default', num_threads=1): import sage.rings.bernmm return sage.rings.bernmm.bernmm_bern_rat(n, num_threads) else: - raise ValueError, "invalid choice of algorithm" + raise ValueError("invalid choice of algorithm") def factorial(n, algorithm='gmp'): @@ -396,13 +396,13 @@ def factorial(n, algorithm='gmp'): calculations.) """ if n < 0: - raise ValueError, "factorial -- must be nonnegative" + raise ValueError("factorial -- must be nonnegative") if algorithm == 'gmp': return ZZ(n).factorial() elif algorithm == 'pari': return pari.factorial(n) else: - raise ValueError, 'unknown algorithm' + raise ValueError('unknown algorithm') def is_prime(n): r""" @@ -465,7 +465,7 @@ def is_prime(n): else: return n.is_pseudoprime() except AttributeError: - raise TypeError, "is_prime() is not written for this type" + raise TypeError("is_prime() is not written for this type") def is_pseudoprime(n, flag=0): r""" @@ -841,7 +841,7 @@ def primes_first_n(n, leave_pari=False): [] """ if n < 0: - raise ValueError, "n must be nonnegative" + raise ValueError("n must be nonnegative") if n < 1: return [] return fast_arith.prime_range(pari.nth_prime(n) + 1) @@ -1138,7 +1138,7 @@ def previous_prime(n): """ n = ZZ(n)-1 if n <= 1: - raise ValueError, "no previous prime" + raise ValueError("no previous prime") if n <= 3: return ZZ(n) if n%2 == 0: @@ -1186,7 +1186,7 @@ def previous_prime_power(n): """ n = ZZ(n)-1 if n <= 0: - raise ValueError, "no previous prime power" + raise ValueError("no previous prime power") while not is_prime_power(n): n -= 1 return n @@ -1256,9 +1256,9 @@ def random_prime(n, proof=None, lbound=2): proof = get_flag(proof, "arithmetic") n = ZZ(n) if n < 2: - raise ValueError, "n must be greater than or equal to 2" + raise ValueError("n must be greater than or equal to 2") if n < lbound: - raise ValueError, "n must be at least lbound: %s"%(lbound) + raise ValueError("n must be at least lbound: %s"%(lbound)) elif n == 2: return n lbound = max(2, lbound) @@ -1274,8 +1274,7 @@ def random_prime(n, proof=None, lbound=2): else: smallest_prime = ZZ(lbound-1).next_probable_prime() if smallest_prime > n: - raise ValueError, \ - "There are no primes between %s and %s (inclusive)" % (lbound, n) + raise ValueError("There are no primes between %s and %s (inclusive)" % (lbound, n)) if proof: prime_test = is_prime @@ -1342,7 +1341,7 @@ def divisors(n): [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300] """ if not n: - raise ValueError, "n must be nonzero" + raise ValueError("n must be nonzero") R = parent(n) if R in [int, long]: @@ -2054,7 +2053,7 @@ def power_mod(a,n,m): ZeroDivisionError: modulus must be nonzero. """ if m==0: - raise ZeroDivisionError, "modulus must be nonzero." + raise ZeroDivisionError("modulus must be nonzero.") if m==1: return 0 if n < 0: @@ -2062,7 +2061,7 @@ def power_mod(a,n,m): return power_mod(ainv, -n, m) if n==0: if a == 0: - raise ArithmeticError, "0^0 is undefined." + raise ArithmeticError("0^0 is undefined.") return 1 apow = a % m @@ -2229,7 +2228,7 @@ def _rational_reconstruction_python(a,m): y *= -1 if x <= bnd and GCD(x,y) == 1: return ZZ(y) / ZZ(x) - raise ValueError, "Rational reconstruction of %s (mod %s) does not exist."%(a,m) + raise ValueError("Rational reconstruction of %s (mod %s) does not exist."%(a,m)) def mqrr_rational_reconstruction(u, m, T): r""" @@ -2471,13 +2470,13 @@ def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds): try: return n.factor(proof=proof, **kwds) except AttributeError: - raise TypeError, "unable to factor n" + raise TypeError("unable to factor n") except TypeError: # Just in case factor method doesn't have a proof option. try: return n.factor(**kwds) except AttributeError: - raise TypeError, "unable to factor n" + raise TypeError("unable to factor n") def radical(n, *args, **kwds): """ @@ -2588,7 +2587,7 @@ def prime_to_m_part(n,m): 21717 """ if n == 0: - raise ValueError, "n must be nonzero." + raise ValueError("n must be nonzero.") if m == 0: return ZZ(1) n = ZZ(n) @@ -2998,9 +2997,9 @@ def CRT_list(v, moduli): """ if not isinstance(v,list) or not isinstance(moduli,list): - raise ValueError, "Arguments to CRT_list should be lists" + raise ValueError("Arguments to CRT_list should be lists") if len(v) != len(moduli): - raise ValueError, "Arguments to CRT_list should be lists of the same length" + raise ValueError("Arguments to CRT_list should be lists of the same length") if len(v) == 0: return ZZ(0) if len(v) == 1: @@ -3085,7 +3084,7 @@ def CRT_vectors(X, moduli): return [] n = len(X) if n != len(moduli): - raise ValueError, "number of moduli must equal length of X" + raise ValueError("number of moduli must equal length of X") a = CRT_basis(moduli) modulus = misc.prod(moduli) return [sum([a[i]*X[i][j] for i in range(n)]) % modulus for j in range(len(X[0]))] @@ -3312,7 +3311,7 @@ def multinomial(*ks): """ if isinstance(ks[0],list): if len(ks) >1: - raise ValueError, "multinomial takes only one list argument" + raise ValueError("multinomial takes only one list argument") ks=ks[0] s, c = 0, 1 @@ -3551,9 +3550,9 @@ def legendre_symbol(x,p): x = QQ(x).numerator() * QQ(x).denominator() p = ZZ(p) if not p.is_prime(): - raise ValueError, "p must be a prime" + raise ValueError("p must be a prime") if p == 2: - raise ValueError, "p must be odd" + raise ValueError("p must be odd") return x.kronecker(p) def jacobi_symbol(a,b): @@ -3596,7 +3595,7 @@ def jacobi_symbol(a,b): """ if b%2==0: - raise ValueError, "second input must be odd, %s is not odd"%b + raise ValueError("second input must be odd, %s is not odd"%b) return kronecker_symbol(a,b) @@ -3702,7 +3701,7 @@ def primitive_root(n, check=True): m = n // 2 if m%2 and m.is_prime_power(): return ZZ(pari(n).znprimroot()) - raise ValueError, "no primitive root" + raise ValueError("no primitive root") def nth_prime(n): """ @@ -4468,7 +4467,7 @@ def number_of_divisors(n): """ m = ZZ(n) if m.is_zero(): - raise ValueError, "input must be nonzero" + raise ValueError("input must be nonzero") return ZZ(pari(m).numdiv()) @@ -4527,7 +4526,7 @@ def hilbert_symbol(a, b, p, algorithm="pari"): """ p = ZZ(p) if p != -1 and not p.is_prime(): - raise ValueError, "p must be prime or -1" + raise ValueError("p must be prime or -1") a = QQ(a).numerator() * QQ(a).denominator() b = QQ(b).numerator() * QQ(b).denominator() @@ -4569,10 +4568,10 @@ def hilbert_symbol(a, b, p, algorithm="pari"): ans_pari = hilbert_symbol(a,b,p,algorithm='pari') ans_direct = hilbert_symbol(a,b,p,algorithm='direct') if ans_pari != ans_direct: - raise RuntimeError, "There is a bug in hilbert_symbol; two ways of computing the Hilbert symbol (%s,%s)_%s disagree"%(a,b,p) + raise RuntimeError("There is a bug in hilbert_symbol; two ways of computing the Hilbert symbol (%s,%s)_%s disagree"%(a,b,p)) return ans_pari else: - raise ValueError, "Algorithm %s not defined"%algorithm + raise ValueError("Algorithm %s not defined"%algorithm) def hilbert_conductor(a, b): @@ -4656,7 +4655,7 @@ def hilbert_conductor_inverse(d): Z = ZZ d = Z(d) if d <= 0: - raise ValueError, "d needs to be positive" + raise ValueError("d needs to be positive") if d == 1: return (Z(-1), Z(1)) if d == 2: @@ -4673,7 +4672,7 @@ def hilbert_conductor_inverse(d): else: mo = moebius(d) if mo == 0: - raise ValueError, "d needs to be squarefree" + raise ValueError("d needs to be squarefree") if d % 2 == 0 and mo*d % 16 != 2: dd = mo * d / 2 else: @@ -4872,7 +4871,7 @@ def integer_ceil(x): return sage.rings.all.Integer(int(math.ceil(float(x)))) except TypeError: pass - raise NotImplementedError, "computation of floor of %s not implemented"%repr(x) + raise NotImplementedError("computation of floor of %s not implemented"%repr(x)) def integer_floor(x): r""" @@ -4905,7 +4904,7 @@ def integer_floor(x): return ZZ(int(math.floor(float(x)))) except TypeError: pass - raise NotImplementedError, "computation of floor of %s not implemented"%x + raise NotImplementedError("computation of floor of %s not implemented"%x) @@ -4937,11 +4936,11 @@ def two_squares(n, algorithm='gap'): import sage.interfaces.gap as gap a = gap.gap.eval('TwoSquares(%s)'%n) if a == 'fail': - raise ValueError, "%s is not a sum of two squares"%n + raise ValueError("%s is not a sum of two squares"%n) x, y = eval(a) return Integer(x), Integer(y) else: - raise RuntimeError, "unknown algorithm '%s'"%algorithm + raise RuntimeError("unknown algorithm '%s'"%algorithm) def _brute_force_four_squares(n): """ @@ -5154,7 +5153,7 @@ def differences(lis, n=1): """ n = ZZ(n) if n < 1: - raise ValueError, 'n must be greater than 0' + raise ValueError('n must be greater than 0') lis = [lis[i + 1] - num for i, num in enumerate(lis[:-1])] if n == 1: return lis diff --git a/src/sage/rings/big_oh.py b/src/sage/rings/big_oh.py index f5cd167e72f..482f94b29ee 100644 --- a/src/sage/rings/big_oh.py +++ b/src/sage/rings/big_oh.py @@ -70,9 +70,9 @@ def O(*x): elif isinstance(x, Polynomial): if x.parent().ngens() != 1: - raise NotImplementedError, "completion only currently defined for univariate polynomials" + raise NotImplementedError("completion only currently defined for univariate polynomials") if not x.is_monomial(): - raise NotImplementedError, "completion only currently defined for the maximal ideal (x)" + raise NotImplementedError("completion only currently defined for the maximal ideal (x)") return x.parent().completion(x.parent().gen())(0, x.degree()) elif isinstance(x, laurent_series_ring_element.LaurentSeries): @@ -80,10 +80,10 @@ def O(*x): elif isinstance(x, (int,long,integer.Integer,rational.Rational)): # p-adic number if x <= 0: - raise ArithmeticError, "x must be a prime power >= 2" + raise ArithmeticError("x must be a prime power >= 2") F = arith.factor(x) if len(F) != 1: - raise ArithmeticError, "x must be prime power" + raise ArithmeticError("x must be prime power") p, r = F[0] if r >= 0: return padics_factory.Zp(p, prec = max(r, 20), type = 'capped-rel')(0, absprec = r) @@ -92,5 +92,5 @@ def O(*x): elif isinstance(x, padic_generic_element.pAdicGenericElement): return x.parent()(0, absprec = x.valuation()) - raise ArithmeticError, "O(x) not defined" + raise ArithmeticError("O(x) not defined") diff --git a/src/sage/rings/complex_field.py b/src/sage/rings/complex_field.py index d01d19dc4e4..0a69a8dc54a 100644 --- a/src/sage/rings/complex_field.py +++ b/src/sage/rings/complex_field.py @@ -504,7 +504,7 @@ def gen(self, n=0): 1.00000000000000*I """ if n != 0: - raise IndexError, "n must be 0" + raise IndexError("n must be 0") return complex_number.ComplexNumber(self, 0, 1) def is_field(self, proof = True): diff --git a/src/sage/rings/complex_interval_field.py b/src/sage/rings/complex_interval_field.py index 0b693acf47c..97b9cf00553 100644 --- a/src/sage/rings/complex_interval_field.py +++ b/src/sage/rings/complex_interval_field.py @@ -470,7 +470,7 @@ def gen(self, n=0): 1*I """ if n != 0: - raise IndexError, "n must be 0" + raise IndexError("n must be 0") return complex_interval.ComplexIntervalFieldElement(self, 0, 1) def random_element(self, *args, **kwds): diff --git a/src/sage/rings/contfrac.py b/src/sage/rings/contfrac.py index 42dcfb94f74..cfd8a42a343 100644 --- a/src/sage/rings/contfrac.py +++ b/src/sage/rings/contfrac.py @@ -254,7 +254,7 @@ def __len__(self): ... TypeError: len() of unsized object """ - raise TypeError, 'len() of unsized object' + raise TypeError('len() of unsized object') def gens(self): """ @@ -278,7 +278,7 @@ def gen(self, n=0): if n == 0: return self(1) else: - raise IndexError, "n must be 0" + raise IndexError("n must be 0") def degree(self): """ @@ -389,7 +389,7 @@ def __init__(self, parent, x, bits=None, nterms=None): x = [ZZ(a) for a in x] for i in range(1,len(x)): if x[i] <= 0: - raise ValueError, "each entry except the first must be positive" + raise ValueError("each entry except the first must be positive") self._x = list(x) else: self._x = [ZZ(a) for a in continued_fraction_list(x, bits=bits, nterms=nterms)] @@ -509,9 +509,9 @@ def pn(self, n): (80143857, 25510582) """ if n < -2: - raise ValueError, "n must be at least -2" + raise ValueError("n must be at least -2") if n > len(self._x): - raise ValueError, "n must be at most %s"%len(self._x) + raise ValueError("n must be at most %s"%len(self._x)) try: return self.__pn[n+2] except AttributeError: @@ -541,9 +541,9 @@ def qn(self, n): (80143857, 25510582) """ if n < -2: - raise ValueError, "n must be at least -2" + raise ValueError("n must be at least -2") if n > len(self._x): - raise ValueError, "n must be at most %s"%len(self._x) + raise ValueError("n must be at most %s"%len(self._x)) try: return self.__qn[n+2] except (AttributeError, IndexError): @@ -764,7 +764,7 @@ def sqrt(self, prec=53, all=False): """ r = self._rational_() if r < 0: - raise ValueError, "self must be positive" + raise ValueError("self must be positive") X = r.sqrt(all=all, prec=prec) if not all: return ContinuedFraction(self.parent(), X) diff --git a/src/sage/rings/finite_rings/conway_polynomials.py b/src/sage/rings/finite_rings/conway_polynomials.py index 7d67556b329..892fef6fe05 100644 --- a/src/sage/rings/finite_rings/conway_polynomials.py +++ b/src/sage/rings/finite_rings/conway_polynomials.py @@ -301,7 +301,7 @@ def _find_pow_of_frobenius(p, n, x, y): if x == y: break y = y**p else: - raise RuntimeError, "No appropriate power of Frobenius found" + raise RuntimeError("No appropriate power of Frobenius found") return mod(i, n) def _crt_non_coprime(running, a): diff --git a/src/sage/rings/finite_rings/element_ext_pari.py b/src/sage/rings/finite_rings/element_ext_pari.py index e9fcf4051a9..074c2c4b59f 100644 --- a/src/sage/rings/finite_rings/element_ext_pari.py +++ b/src/sage/rings/finite_rings/element_ext_pari.py @@ -261,15 +261,15 @@ def __init__(self, parent, value, value_from_pari=False): value = value.Mod(parent._pari_modulus()) self.__value = value * parent._pari_one() except RuntimeError: - raise TypeError, "no possible coercion implemented" + raise TypeError("no possible coercion implemented") elif isinstance(value, FiniteField_ext_pariElement): if parent != value.parent(): - raise TypeError, "no coercion implemented" + raise TypeError("no coercion implemented") else: self.__value = value.__value elif isinstance(value, FreeModuleElement): if parent.vector_space() != value.parent(): - raise TypeError, "e.parent must match self.vector_space" + raise TypeError("e.parent must match self.vector_space") self.__value = pari(0).Mod(parent._pari_modulus())*parent._pari_one() for i in range(len(value)): self.__value = self.__value + pari(int(value[i])).Mod(parent._pari_modulus())*pari("a^%s"%i) @@ -299,15 +299,15 @@ def __init__(self, parent, value, value_from_pari=False): GFp = parent.prime_subfield() self.__value = pari([GFp(c) for c in value]).Polrev("a").Mod(parent._pari_modulus()) elif isinstance(value, str): - raise TypeError, "value must not be a string" + raise TypeError("value must not be a string") else: try: self.__value = pari(value).Mod(parent._pari_modulus())*parent._pari_one() except RuntimeError: - raise TypeError, "no coercion implemented" + raise TypeError("no coercion implemented") except (AttributeError, TypeError): - raise TypeError, "unable to coerce" + raise TypeError("unable to coerce") def __hash__(self): """ @@ -439,7 +439,7 @@ def square_root(self, extend=False, all=False): if all: return [] else: - raise ValueError, "must be a perfect square." + raise ValueError("must be a perfect square.") def sqrt(self, extend=False, all = False): """ @@ -469,10 +469,10 @@ def rational_reconstruction(self): 2/3 """ if self.parent().degree() != 1: - raise ArithmeticError, "finite field must be prime" + raise ArithmeticError("finite field must be prime") t = arith.rational_reconstruction(int(self), self.parent().characteristic()) if t == None or t[1] == 0: - raise ZeroDivisionError, "unable to compute rational reconstruction" + raise ZeroDivisionError("unable to compute rational reconstruction") return rational.Rational((t[0],t[1])) def multiplicative_order(self): @@ -629,7 +629,7 @@ def _gap_init_(self): """ F = self.parent() if F.order() > 65536: - raise TypeError, "order must be at most 65536" + raise TypeError("order must be at most 65536") if self == 0: return '0*Z(%s)'%F.order() @@ -717,7 +717,7 @@ def __int__(self): try: return int(self.__value.lift().lift()) except ValueError: - raise TypeError, "cannot coerce to int" + raise TypeError("cannot coerce to int") def _integer_(self, ZZ=None): """ @@ -748,7 +748,7 @@ def __long__(self): try: return long(self.__value.lift().lift()) except ValueError: - raise TypeError, "cannot coerce to long" + raise TypeError("cannot coerce to long") def __float__(self): """ @@ -763,7 +763,7 @@ def __float__(self): try: return float(self.__value.lift().lift()) except ValueError: - raise TypeError, "cannot coerce to float" + raise TypeError("cannot coerce to float") def __pow__(self, _right): """ @@ -835,7 +835,7 @@ def __abs__(self): ... ArithmeticError: absolute value not defined """ - raise ArithmeticError, "absolute value not defined" + raise ArithmeticError("absolute value not defined") def __invert__(self): """ @@ -852,7 +852,7 @@ def __invert__(self): """ if self.__value == 0: - raise ZeroDivisionError, "Cannot invert 0" + raise ZeroDivisionError("Cannot invert 0") return FiniteField_ext_pariElement(self.parent(), ~self.__value, value_from_pari=True) def lift(self): diff --git a/src/sage/rings/finite_rings/finite_field_ext_pari.py b/src/sage/rings/finite_rings/finite_field_ext_pari.py index f8666025bbb..a43925a7240 100644 --- a/src/sage/rings/finite_rings/finite_field_ext_pari.py +++ b/src/sage/rings/finite_rings/finite_field_ext_pari.py @@ -179,7 +179,7 @@ def __init__(self, q, name, modulus=None): from constructor import FiniteField as GF q = integer.Integer(q) if q < 2: - raise ArithmeticError, "q must be a prime power" + raise ArithmeticError("q must be a prime power") from sage.structure.proof.all import arithmetic proof = arithmetic() if proof: @@ -188,12 +188,12 @@ def __init__(self, q, name, modulus=None): from sage.rings.arith import is_pseudoprime_small_power F = is_pseudoprime_small_power(q, get_data=True) if len(F) != 1: - raise ArithmeticError, "q must be a prime power" + raise ArithmeticError("q must be a prime power") if F[0][1] > 1: base_ring = GF(F[0][0]) else: - raise ValueError, "The size of the finite field must not be prime." + raise ValueError("The size of the finite field must not be prime.") #base_ring = self FiniteField_generic.__init__(self, base_ring, name, normalize=True) @@ -521,14 +521,14 @@ def _element_constructor_(self, x): return element_ext_pari.FiniteField_ext_pariElement(self, x) else: # This is where we *would* do coercion from one finite field to another... - raise TypeError, "no coercion defined" + raise TypeError("no coercion defined") elif sage.interfaces.gap.is_GapElement(x): from sage.interfaces.gap import gfq_gap_to_sage try: return gfq_gap_to_sage(x, self) except (ValueError, IndexError, TypeError): - raise TypeError, "no coercion defined" + raise TypeError("no coercion defined") if isinstance(x, (int, long, integer.Integer, rational.Rational, pari.pari_gen, list)): @@ -539,7 +539,7 @@ def _element_constructor_(self, x): if x.is_constant(): return self(x.constant_coefficient()) else: - raise TypeError, "no coercion defined" + raise TypeError("no coercion defined") elif isinstance(x, polynomial_element.Polynomial): if x.is_constant(): @@ -557,7 +557,7 @@ def _element_constructor_(self, x): return self(x) if t[2] == 'I': #t_INT and t_INTMOD return self(x) - raise TypeError, "string element does not match this finite field" + raise TypeError("string element does not match this finite field") try: if x.parent() == self.vector_space(): @@ -568,7 +568,7 @@ def _element_constructor_(self, x): try: return element_ext_pari.FiniteField_ext_pariElement(self, integer.Integer(x)) except TypeError as msg: - raise TypeError, "%s\nno coercion defined"%msg + raise TypeError("%s\nno coercion defined"%msg) def __len__(self): """ diff --git a/src/sage/rings/finite_rings/finite_field_givaro.py b/src/sage/rings/finite_rings/finite_field_givaro.py index 31101afbd78..7c6e89c5c69 100644 --- a/src/sage/rings/finite_rings/finite_field_givaro.py +++ b/src/sage/rings/finite_rings/finite_field_givaro.py @@ -104,19 +104,19 @@ def __init__(self, q, name="a", modulus=None, repr="poly", cache=False): self._kwargs = {} if repr not in ['int', 'log', 'poly']: - raise ValueError, "Unknown representation %s"%repr + raise ValueError("Unknown representation %s"%repr) q = Integer(q) if q < 2: - raise ValueError, "q must be a prime power" + raise ValueError("q must be a prime power") F = q.factor() if len(F) > 1: - raise ValueError, "q must be a prime power" + raise ValueError("q must be a prime power") p = F[0][0] k = F[0][1] if q >= 1<<16: - raise ValueError, "q must be < 2^16" + raise ValueError("q must be < 2^16") import constructor FiniteField.__init__(self, constructor.FiniteField(p), name, normalize=False) @@ -133,7 +133,7 @@ def __init__(self, q, name="a", modulus=None, repr="poly", cache=False): elif modulus is None: modulus = 'random' else: - raise ValueError, "Conway polynomial not found" + raise ValueError("Conway polynomial not found") from sage.rings.polynomial.all import is_Polynomial if is_Polynomial(modulus): @@ -385,7 +385,7 @@ def gen(self, n=0): 1 """ if n > 0: - raise IndexError, "only one generator" + raise IndexError("only one generator") return self._cache.gen() def prime_subfield(self): diff --git a/src/sage/rings/finite_rings/finite_field_prime_modn.py b/src/sage/rings/finite_rings/finite_field_prime_modn.py index a31329a6566..c2ee45936b0 100644 --- a/src/sage/rings/finite_rings/finite_field_prime_modn.py +++ b/src/sage/rings/finite_rings/finite_field_prime_modn.py @@ -76,7 +76,7 @@ def __init__(self, p, name=None, check=True): """ p = integer.Integer(p) if check and not arith.is_prime(p): - raise ArithmeticError, "p must be prime" + raise ArithmeticError("p must be prime") self.__char = p self._kwargs = {} # FiniteField_generic does nothing more than IntegerModRing_generic, and @@ -302,7 +302,7 @@ def gen(self, n=0): IndexError: only one generator """ if n != 0: - raise IndexError, "only one generator" + raise IndexError("only one generator") return self(1) def __iter__(self): diff --git a/src/sage/rings/finite_rings/homset.py b/src/sage/rings/finite_rings/homset.py index fc109de218d..9577a9a0b2b 100644 --- a/src/sage/rings/finite_rings/homset.py +++ b/src/sage/rings/finite_rings/homset.py @@ -94,7 +94,7 @@ def __call__(self, im_gens, check=True): try: return self._coerce_impl(im_gens) except TypeError: - raise TypeError, "images do not define a valid homomorphism" + raise TypeError("images do not define a valid homomorphism") def _coerce_impl(self, x): """ diff --git a/src/sage/rings/fraction_field.py b/src/sage/rings/fraction_field.py index 01ac07fbc28..75cf6009bbc 100644 --- a/src/sage/rings/fraction_field.py +++ b/src/sage/rings/fraction_field.py @@ -123,9 +123,9 @@ def FractionField(R, names=None): TypeError: R must be an integral domain. """ if not ring.is_Ring(R): - raise TypeError, "R must be a ring" + raise TypeError("R must be a ring") if not R.is_integral_domain(): - raise TypeError, "R must be an integral domain." + raise TypeError("R must be an integral domain.") return R.fraction_field() def is_FractionField(x): diff --git a/src/sage/rings/function_field/function_field.py b/src/sage/rings/function_field/function_field.py index 2a54d8970e4..95fa943a8a7 100644 --- a/src/sage/rings/function_field/function_field.py +++ b/src/sage/rings/function_field/function_field.py @@ -396,14 +396,14 @@ def __init__(self, polynomial, names, """ from sage.rings.polynomial.all import is_Polynomial if polynomial.parent().ngens()>1 or not is_Polynomial(polynomial): - raise TypeError, "polynomial must be univariate a polynomial" + raise TypeError("polynomial must be univariate a polynomial") if names is None: names = (polynomial.variable_name(), ) if polynomial.degree() <= 0: - raise ValueError, "polynomial must have positive degree" + raise ValueError("polynomial must have positive degree") base_field = polynomial.base_ring() if not isinstance(base_field, FunctionField): - raise TypeError, "polynomial must be over a FunctionField" + raise TypeError("polynomial must be over a FunctionField") self._element_class = element_class self._element_init_pass_parent = False self._base_field = base_field @@ -785,7 +785,7 @@ def gen(self, n=0): ... IndexError: Only one generator. """ - if n != 0: raise IndexError, "Only one generator." + if n != 0: raise IndexError("Only one generator.") return self._gen def ngens(self): @@ -918,12 +918,12 @@ def hom(self, im_gens, base_morphism=None): Morphism of function fields defined by xx |--> x, yy |--> y """ if base_morphism is not None: - raise NotImplementedError, "Function field homorphisms with optional argument base_morphism are not implemented yet. Please specify the images of the generators of the base fields manually." + raise NotImplementedError("Function field homorphisms with optional argument base_morphism are not implemented yet. Please specify the images of the generators of the base fields manually.") if not isinstance(im_gens, (list,tuple)): im_gens = [im_gens] if len(im_gens) == 0: - raise ValueError, "no images specified" + raise ValueError("no images specified") if len(im_gens) > 1: base_morphism = self.base_field().hom(im_gens[1:], base_morphism) @@ -965,7 +965,7 @@ def genus(self): return int(curveIdeal._singular_().genus()) else: - raise NotImplementedError, "Computation of genus over this rational function field not implemented yet" + raise NotImplementedError("Computation of genus over this rational function field not implemented yet") def is_RationalFunctionField(x): """ @@ -1049,11 +1049,11 @@ def __init__(self, constant_field, names, TypeError: constant_field must be a field """ if names is None: - raise ValueError, "variable name must be specified" + raise ValueError("variable name must be specified") elif not isinstance(names, tuple): names = (names, ) if not constant_field.is_field(): - raise TypeError, "constant_field must be a field" + raise TypeError("constant_field must be a field") self._element_class = element_class self._element_init_pass_parent = False Field.__init__(self, self, names=names, category = category) @@ -1307,7 +1307,7 @@ def gen(self, n=0): IndexError: Only one generator. """ if n != 0: - raise IndexError, "Only one generator." + raise IndexError("Only one generator.") return self._gen def ngens(self): @@ -1374,7 +1374,7 @@ def hom(self, im_gens, base_morphism=None): if not isinstance(im_gens, (list,tuple)): im_gens = [im_gens] if len(im_gens) != 1: - raise ValueError, "there must be exactly one generator" + raise ValueError("there must be exactly one generator") x = im_gens[0] from maps import FunctionFieldMorphism_rational return FunctionFieldMorphism_rational(self.Hom(x.parent()), x) diff --git a/src/sage/rings/function_field/function_field_ideal.py b/src/sage/rings/function_field/function_field_ideal.py index 3ba22053af3..1b883fbfde8 100644 --- a/src/sage/rings/function_field/function_field_ideal.py +++ b/src/sage/rings/function_field/function_field_ideal.py @@ -199,7 +199,7 @@ def intersection(self, other): if not isinstance(other, FunctionFieldIdeal_module): other = self.ring().ideal(other) if self.ring() != other.ring(): - raise ValueError, "rings must be the same" + raise ValueError("rings must be the same") return FunctionFieldIdeal_module(self.ring(), self.module().intersection(other.module())) def __cmp__(self, other): @@ -224,7 +224,7 @@ def __cmp__(self, other): if not isinstance(other, FunctionFieldIdeal_module): other = self.ring().ideal(other) if self.ring() != other.ring(): - raise ValueError, "rings must be the same" + raise ValueError("rings must be the same") return cmp(self.module(), other.module()) def __invert__(self): diff --git a/src/sage/rings/function_field/function_field_order.py b/src/sage/rings/function_field/function_field_order.py index d04731f37f2..4b2ec6680e2 100644 --- a/src/sage/rings/function_field/function_field_order.py +++ b/src/sage/rings/function_field/function_field_order.py @@ -252,11 +252,11 @@ def __init__(self, basis, check=True): ValueError: Basis [y, y, y^3, y^4, 2*x*y + (x^4 + 1)/x] is not linearly independent """ if len(basis) == 0: - raise ValueError, "basis must have positive length" + raise ValueError("basis must have positive length") fraction_field = basis[0].parent() if len(basis) != fraction_field.degree(): - raise ValueError, "length of basis must equal degree of field" + raise ValueError("length of basis must equal degree of field") FunctionFieldOrder.__init__(self, fraction_field) @@ -268,11 +268,11 @@ def __init__(self, basis, check=True): self._populate_coercion_lists_(coerce_list=[self._ring]) if check: if self._module.rank() != fraction_field.degree(): - raise ValueError, "Basis %s is not linearly independent"%(basis) + raise ValueError("Basis %s is not linearly independent"%(basis)) if not to(fraction_field(1)) in self._module: - raise ValueError, "The identity element must be in the module spanned by basis %s"%(basis) + raise ValueError("The identity element must be in the module spanned by basis %s"%(basis)) if not all(to(a*b) in self._module for a in basis for b in basis): - raise ValueError, "The module generated by basis %s must be closed under multiplication"%(basis) + raise ValueError("The module generated by basis %s must be closed under multiplication"%(basis)) IntegralDomain.__init__(self, self, names = fraction_field.variable_names(), normalize = False) def _element_constructor_(self, f, check=True): @@ -299,7 +299,7 @@ def _element_constructor_(self, f, check=True): V, fr, to = fraction_field.vector_space() f_vector = to(fraction_field(f)) if not f_vector in self._module: - raise ValueError, "%s is not an element of %s"%(f_vector,self) + raise ValueError("%s is not an element of %s"%(f_vector,self)) return fraction_field._element_class(self, f) def fraction_field(self): @@ -452,7 +452,7 @@ def gen(self, n=0): ... IndexError: Only one generator. """ - if n != 0: raise IndexError, "Only one generator." + if n != 0: raise IndexError("Only one generator.") return self._gen def ngens(self): diff --git a/src/sage/rings/function_field/maps.py b/src/sage/rings/function_field/maps.py index 6ae45156716..4763d1d3501 100644 --- a/src/sage/rings/function_field/maps.py +++ b/src/sage/rings/function_field/maps.py @@ -337,7 +337,7 @@ def __init__(self, parent, im_gen, base_morphism): v = [base_morphism(a) for a in v] f = R(v) if f(im_gen): - raise ValueError, "invalid morphism" + raise ValueError("invalid morphism") def _call_(self, x): """ diff --git a/src/sage/rings/homset.py b/src/sage/rings/homset.py index e5df900cc3d..28a1c58ed81 100644 --- a/src/sage/rings/homset.py +++ b/src/sage/rings/homset.py @@ -181,7 +181,7 @@ def __call__(self, im_gens, check=True): try: return self._coerce_impl(im_gens) except TypeError: - raise TypeError, "images do not define a valid homomorphism" + raise TypeError("images do not define a valid homomorphism") def natural_map(self): @@ -265,7 +265,7 @@ def __call__(self, im_gens, check=True): try: return self._coerce_impl(im_gens) except TypeError: - raise TypeError, "images do not define a valid homomorphism" + raise TypeError("images do not define a valid homomorphism") def _coerce_impl(self, x): """ diff --git a/src/sage/rings/ideal.py b/src/sage/rings/ideal.py index 8c34becd67a..40efcc9ff66 100644 --- a/src/sage/rings/ideal.py +++ b/src/sage/rings/ideal.py @@ -168,9 +168,9 @@ def Ideal(*args, **kwds): True """ if len(args) == 0: - raise ValueError, "need at least one argument" + raise ValueError("need at least one argument") if len(args) == 1 and args[0] == []: - raise ValueError, "unable to determine which ring to embed the ideal in" + raise ValueError("unable to determine which ring to embed the ideal in") first = args[0] @@ -190,7 +190,7 @@ def Ideal(*args, **kwds): gens = args[1:] if not commutative_ring.is_CommutativeRing(R): - raise TypeError, "R must be a commutative ring" + raise TypeError("R must be a commutative ring") return R.ideal(*gens, **kwds) @@ -508,7 +508,7 @@ def apply_morphism(self, phi): """ from sage.categories.morphism import is_Morphism if not is_Morphism(phi): - raise TypeError, "phi must be a morphism" + raise TypeError("phi must be a morphism") # delegate: morphisms know how to apply themselves to ideals return phi(self) @@ -1518,11 +1518,11 @@ def residue_field(self): TypeError: residue fields only supported for polynomial rings over finite fields. """ if not self.is_prime(): - raise ValueError, "The ideal (%s) is not prime"%self + raise ValueError("The ideal (%s) is not prime"%self) from sage.rings.integer_ring import ZZ if self.ring() is ZZ: return ZZ.residue_field(self, check = False) - raise NotImplementedError, "residue_field() is only implemented for ZZ and rings of integers of number fields." + raise NotImplementedError("residue_field() is only implemented for ZZ and rings of integers of number fields.") class Ideal_fractional(Ideal_generic): """ @@ -1594,7 +1594,7 @@ def Cyclic(R, n=None, homog=False, singular=singular_default): if n: if n > R.ngens(): - raise ArithmeticError, "n must be <= R.ngens()" + raise ArithmeticError("n must be <= R.ngens()") else: n = R.ngens() @@ -1642,7 +1642,7 @@ def Katsura(R, n=None, homog=False, singular=singular_default): from rational_field import RationalField if n: if n > R.ngens(): - raise ArithmeticError, "n must be <= R.ngens()." + raise ArithmeticError("n must be <= R.ngens().") else: n = R.ngens() singular.lib("poly") @@ -1689,6 +1689,6 @@ def FieldIdeal(R): q = R.base_ring().order() if q is sage.rings.infinity.infinity: - raise TypeError, "Cannot construct field ideal for R.base_ring().order()==infinity" + raise TypeError("Cannot construct field ideal for R.base_ring().order()==infinity") return R.ideal([x**q - x for x in R.gens() ]) diff --git a/src/sage/rings/infinity.py b/src/sage/rings/infinity.py index 5074ed7a9f1..2c95ed0a43f 100644 --- a/src/sage/rings/infinity.py +++ b/src/sage/rings/infinity.py @@ -274,7 +274,7 @@ def _pari_(self): ... TypeError: cannot convert infinity to Pari """ - raise TypeError, 'cannot convert infinity to Pari' + raise TypeError('cannot convert infinity to Pari') def _latex_(self): r""" @@ -352,7 +352,7 @@ def _add_(self, other): """ if isinstance(other, AnInfinity): if self._sign != other._sign: - raise SignError, "cannot add infinity to minus infinity" + raise SignError("cannot add infinity to minus infinity") return self def _sub_(self, other): @@ -380,9 +380,9 @@ def _sub_(self, other): """ if isinstance(other, AnInfinity): if self._sign == 0: - raise ValueError, "oo - oo not defined" + raise ValueError("oo - oo not defined") elif self._sign == other._sign: - raise SignError, "cannot add infinity to minus infinity" + raise SignError("cannot add infinity to minus infinity") return self def _mul_(self, other): @@ -408,7 +408,7 @@ def _mul_(self, other): return -self if other > 0: return self - raise SignError, "cannot multiply infinity by zero" + raise SignError("cannot multiply infinity by zero") def _div_(self, other): """ @@ -517,7 +517,7 @@ def fraction_field(self): ... TypeError: infinity 'ring' has no fraction field """ - raise TypeError, "infinity 'ring' has no fraction field" + raise TypeError("infinity 'ring' has no fraction field") def gen(self, n=0): """ @@ -539,7 +539,7 @@ def gen(self, n=0): self._gen = UnsignedInfinity() return self._gen else: - raise IndexError, "UnsignedInfinityRing only has one generator" + raise IndexError("UnsignedInfinityRing only has one generator") def gens(self): """ @@ -715,7 +715,7 @@ def _mul_(self, other): Infinity """ if isinstance(other, UnsignedInfinity): - raise ValueError, "oo times number < oo not defined" + raise ValueError("oo times number < oo not defined") return self def _div_(self, other): @@ -733,7 +733,7 @@ def _div_(self, other): """ if isinstance(other, UnsignedInfinity): return ZZ(0) - raise ValueError, "quotient of number < oo by number < oo not defined" + raise ValueError("quotient of number < oo by number < oo not defined") def __cmp__(self, other): """ @@ -784,7 +784,7 @@ def _mul_(self, other): """ if isinstance(other, UnsignedInfinity): return self - raise ValueError, "unsigned oo times smaller number not defined" + raise ValueError("unsigned oo times smaller number not defined") unsigned_infinity = UnsignedInfinityRing.gen(0) @@ -840,7 +840,7 @@ def fraction_field(self): ... TypeError: infinity 'ring' has no fraction field """ - raise TypeError, "infinity 'ring' has no fraction field" + raise TypeError("infinity 'ring' has no fraction field") def ngens(self): """ @@ -876,7 +876,7 @@ def gen(self, n=0): elif n == 1: return self._gen1 else: - raise IndexError, "n must be 0 or 1" + raise IndexError("n must be 0 or 1") except AttributeError: if n == 0: self._gen0 = PlusInfinity() @@ -1049,7 +1049,7 @@ def _add_(self, other): if isinstance(other, InfinityElement): return other if self.value * other.value < 0: - raise SignError, "cannot add positive finite value to negative finite value" + raise SignError("cannot add positive finite value to negative finite value") return FiniteNumber(self.parent(), self.value) def _mul_(self, other): @@ -1076,7 +1076,7 @@ def _mul_(self, other): """ if other.is_zero(): if isinstance(self, InfinityElement): - raise SignError, "cannot multiply infinity by zero" + raise SignError("cannot multiply infinity by zero") return ZZ(0) if self.value < 0: if isinstance(other, InfinityElement): @@ -1088,7 +1088,7 @@ def _mul_(self, other): return FiniteNumber(self.parent(), self.value * other.value) if self.value == 0: if isinstance(other, InfinityElement): - raise SignError, "cannot multiply infinity by zero" + raise SignError("cannot multiply infinity by zero") return ZZ(0) def _div_(self, other): @@ -1140,7 +1140,7 @@ def __invert__(self): ZeroDivisionError: Cannot divide by zero """ if self.value == 0: - raise ZeroDivisionError, "Cannot divide by zero" + raise ZeroDivisionError("Cannot divide by zero") return self def _neg_(self): @@ -1221,7 +1221,7 @@ def sqrt(self): SignError: cannot take square root of a negative number """ if self.value < 0: - raise SignError, "cannot take square root of a negative number" + raise SignError("cannot take square root of a negative number") return self class MinusInfinity(_uniq, AnInfinity, MinusInfinityElement): @@ -1258,7 +1258,7 @@ def sqrt(self): ... SignError: cannot take square root of negative infinity """ - raise SignError, "cannot take square root of negative infinity" + raise SignError("cannot take square root of negative infinity") def _sympy_(self): """ diff --git a/src/sage/rings/laurent_series_ring.py b/src/sage/rings/laurent_series_ring.py index 962940ddfc8..4954738fe4f 100644 --- a/src/sage/rings/laurent_series_ring.py +++ b/src/sage/rings/laurent_series_ring.py @@ -80,7 +80,7 @@ def LaurentSeriesRing(base_ring, name=None, names=None, default_prec=20, sparse= """ if not names is None: name = names if name is None: - raise TypeError, "You must specify the name of the indeterminate of the Laurent series ring." + raise TypeError("You must specify the name of the indeterminate of the Laurent series ring.") global laurent_series key = (base_ring, name, default_prec, sparse) @@ -95,7 +95,7 @@ def LaurentSeriesRing(base_ring, name=None, names=None, default_prec=20, sparse= elif isinstance(base_ring, commutative_ring.CommutativeRing): R = LaurentSeriesRing_generic(base_ring, name, default_prec, sparse) else: - raise TypeError, "base_ring must be a commutative ring" + raise TypeError("base_ring must be a commutative ring") laurent_series[key] = weakref.ref(R) return R @@ -172,7 +172,7 @@ def base_extend(self, R): if R.has_coerce_map_from(self.base_ring()): return self.change_ring(R) else: - raise TypeError, "no valid base extension defined" + raise TypeError("no valid base extension defined") def change_ring(self, R): """ @@ -381,7 +381,7 @@ def _coerce_impl(self, x): if self.has_coerce_map_from(P.base_ring()): return self(x) else: - raise TypeError, "no natural map between bases of power series rings" + raise TypeError("no natural map between bases of power series rings") except AttributeError: pass @@ -532,7 +532,7 @@ def gen(self, n=0): x """ if n != 0: - raise IndexError, "Generator n not defined." + raise IndexError("Generator n not defined.") try: return self.__generator except AttributeError: diff --git a/src/sage/rings/misc.py b/src/sage/rings/misc.py index 62a3dc61db7..19d20819ad4 100644 --- a/src/sage/rings/misc.py +++ b/src/sage/rings/misc.py @@ -33,5 +33,5 @@ def composite_field(K, L): """ C = Sequence([K(0), L(0)]).universe() if C not in _Fields: - raise ValueError, "unable to find a common field" + raise ValueError("unable to find a common field") return C diff --git a/src/sage/rings/monomials.py b/src/sage/rings/monomials.py index d2dcfb00839..49ba87c5b96 100644 --- a/src/sage/rings/monomials.py +++ b/src/sage/rings/monomials.py @@ -60,7 +60,7 @@ def monomials(v, n): """ if (len(v) != len(n)): - raise ValueError, "inputs must be of the same length." + raise ValueError("inputs must be of the same length.") if len(v) == 0: return [] v = Sequence(v) diff --git a/src/sage/rings/number_field/galois_group.py b/src/sage/rings/number_field/galois_group.py index 2055e60da0b..fbb4ab0f02b 100644 --- a/src/sage/rings/number_field/galois_group.py +++ b/src/sage/rings/number_field/galois_group.py @@ -383,7 +383,7 @@ def decomposition_group(self, P): 2 """ if not self.is_galois(): - raise TypeError, "Decomposition groups only defined for Galois extensions" + raise TypeError("Decomposition groups only defined for Galois extensions") if isinstance(P, NumberFieldHomomorphism_im_gens): if self.number_field().is_totally_real(): @@ -393,7 +393,7 @@ def decomposition_group(self, P): else: P = self.number_field().ideal_monoid()(P) if not P.is_prime(): - raise ValueError, "%s is not prime" % P + raise ValueError("%s is not prime" % P) return self.subgroup([s for s in self if s(P) == P]) def complex_conjugation(self, P=None): @@ -420,20 +420,20 @@ def complex_conjugation(self, P=None): if P is None: Q = self.number_field().specified_complex_embedding() if Q is None: - raise ValueError, "No default complex embedding specified" + raise ValueError("No default complex embedding specified") P = Q P = refine_embedding(P, infinity) if not self.number_field().is_galois(): - raise TypeError, "Extension is not Galois" + raise TypeError("Extension is not Galois") if self.number_field().is_totally_real(): - raise TypeError, "No complex conjugation (field is real)" + raise TypeError("No complex conjugation (field is real)") g = self.number_field().gen() gconj = P(g).conjugate() elts = [s for s in self if P(s(g)) == gconj] - if len(elts) != 1: raise ArithmeticError, "Something has gone very wrong here" + if len(elts) != 1: raise ArithmeticError("Something has gone very wrong here") return elts[0] def ramification_group(self, P, v): @@ -453,10 +453,10 @@ def ramification_group(self, P, v): Subgroup [()] of Galois group of Number Field in b with defining polynomial x^6 + 243 """ if not self.is_galois(): - raise TypeError, "Ramification groups only defined for Galois extensions" + raise TypeError("Ramification groups only defined for Galois extensions") P = self.number_field().ideal_monoid()(P) if not P.is_prime(): - raise ValueError, "%s is not prime" + raise ValueError("%s is not prime") return self.subgroup([g for g in self if g(P) == P and g.ramification_degree(P) >= v + 1]) def inertia_group(self, P): @@ -474,7 +474,7 @@ def inertia_group(self, P): Subgroup [()] of Galois group of Number Field in b with defining polynomial x^2 - 3 """ if not self.is_galois(): - raise TypeError, "Inertia groups only defined for Galois extensions" + raise TypeError("Inertia groups only defined for Galois extensions") return self.ramification_group(P, 0) def ramification_breaks(self, P): @@ -494,7 +494,7 @@ def ramification_breaks(self, P): 2 """ if not self.is_galois(): - raise TypeError, "Ramification breaks only defined for Galois extensions" + raise TypeError("Ramification breaks only defined for Galois extensions") from sage.rings.infinity import infinity from sage.sets.set import Set i = [g.ramification_degree(P) - 1 for g in self.decomposition_group(P)] @@ -527,11 +527,11 @@ def artin_symbol(self, P): ValueError: Fractional ideal (...) is ramified """ if not self.is_galois(): - raise TypeError, "Artin symbols only defined for Galois extensions" + raise TypeError("Artin symbols only defined for Galois extensions") P = self.number_field().ideal_monoid()(P) if not P.is_prime(): - raise ValueError, "%s is not prime" % P + raise ValueError("%s is not prime" % P) p = P.smallest_integer() t = [] gens = self.number_field().ring_of_integers().ring_generators() @@ -539,7 +539,7 @@ def artin_symbol(self, P): w = [ (s(g) - g**p).valuation(P) for g in gens] if min(w) >= 1: t.append(s) - if len(t) > 1: raise ValueError, "%s is ramified" % P + if len(t) > 1: raise ValueError("%s is ramified" % P) return t[0] class GaloisGroup_subgroup(GaloisGroup_v2): @@ -681,7 +681,7 @@ def ramification_degree(self, P): 4 """ if not self.parent().is_galois(): - raise TypeError, "Ramification degree only defined for Galois extensions" + raise TypeError("Ramification degree only defined for Galois extensions") gens = self.parent().number_field().ring_of_integers().ring_generators() w = [ (self(g) - g).valuation(P) for g in gens] return min(w) diff --git a/src/sage/rings/number_field/morphism.py b/src/sage/rings/number_field/morphism.py index 2577675a6e6..2ff0baaf0cb 100644 --- a/src/sage/rings/number_field/morphism.py +++ b/src/sage/rings/number_field/morphism.py @@ -46,7 +46,7 @@ def __call__(self, im_gens, check=True): try: return self._coerce_impl(im_gens) except TypeError: - raise TypeError, "images do not define a valid homomorphism" + raise TypeError("images do not define a valid homomorphism") def _coerce_impl(self, x): r""" @@ -92,7 +92,7 @@ def _an_element_(self): if len(L) != 0: return L[0] else: - raise ValueError, "Set is empty" + raise ValueError("Set is empty") def _repr_(self): r""" @@ -252,7 +252,7 @@ def __invert__(self): K = self.domain() L = self.codomain() if K.degree() != L.degree(): - raise TypeError, "Can only invert isomorphisms" + raise TypeError("Can only invert isomorphisms") V, V_into_K, _ = K.vector_space() _, _, L_into_W = L.vector_space() linear_inverse = ~V.hom(map(L_into_W*self*V_into_K, V.basis())) @@ -315,7 +315,7 @@ def preimage(self, y): try: xvec = M.solve_right(yvec) # solve the linear system, throws an exception if there is no solution except ValueError: - raise ValueError, "Element '%s' is not in the image of this homomorphism."%y + raise ValueError("Element '%s' is not in the image of this homomorphism."%y) return VtoK(xvec) # pass from the vector space representation of K back to a point in K class RelativeNumberFieldHomset(NumberFieldHomset): @@ -384,12 +384,12 @@ def __call__(self, im_gen, base_hom=None, check=True): abs_hom = im_gen K = abs_hom.domain() if K != self.domain().absolute_field(K.variable_name()): - raise TypeError, "domain of morphism must be absolute field of domain." + raise TypeError("domain of morphism must be absolute field of domain.") from_K, to_K = K.structure() if abs_hom.domain() != K: - raise ValueError, "domain of absolute homomorphism must be absolute field of domain." + raise ValueError("domain of absolute homomorphism must be absolute field of domain.") if abs_hom.codomain() != self.codomain(): - raise ValueError, "codomain of absolute homomorphism must be codomain of this homset." + raise ValueError("codomain of absolute homomorphism must be codomain of this homset.") return RelativeNumberFieldHomomorphism_from_abs(self, abs_hom) if isinstance(im_gen, RelativeNumberFieldHomomorphism_from_abs): return self._coerce_impl(im_gen) @@ -470,7 +470,7 @@ def default_base_hom(self): pass v = self.domain().base_field().embeddings(self.codomain()) if len(v) == 0: - raise ValueError, "no way to map base field to codomain." + raise ValueError("no way to map base field to codomain.") self.__default_base_hom = v[0] return v[0] @@ -663,7 +663,7 @@ def __call__(self, im_gens, check=True): try: return self._coerce_impl(im_gens) except TypeError: - raise TypeError, "images do not define a valid homomorphism" + raise TypeError("images do not define a valid homomorphism") def _coerce_impl(self, x): r""" diff --git a/src/sage/rings/number_field/number_field.py b/src/sage/rings/number_field/number_field.py index a2ceb3b4fe3..01fb95a66db 100644 --- a/src/sage/rings/number_field/number_field.py +++ b/src/sage/rings/number_field/number_field.py @@ -420,7 +420,7 @@ def NumberField(polynomial, name=None, check=True, names=None, cache=True, """ if name is None and names is None: - raise TypeError, "You must specify the name of the generator." + raise TypeError("You must specify the name of the generator.") if not names is None: name = names @@ -433,7 +433,7 @@ def NumberField(polynomial, name=None, check=True, names=None, cache=True, try: polynomial = polynomial.polynomial(QQ) except (AttributeError, TypeError): - raise TypeError, "polynomial (=%s) must be a polynomial."%repr(polynomial) + raise TypeError("polynomial (=%s) must be a polynomial."%repr(polynomial)) # convert ZZ to QQ R = polynomial.base_ring() @@ -575,7 +575,7 @@ def NumberFieldTower(v, names, check=True, embeddings=None): embeddings = [None] * len(v) if not isinstance(v, (list, tuple)): - raise TypeError, "v must be a list or tuple" + raise TypeError("v must be a list or tuple") if len(v) == 0: return QQ if len(v) == 1: @@ -724,7 +724,7 @@ def QuadraticField(D, name='a', check=True, embedding=True, latex_name='sqrt', * D = QQ(D) if check: if D.is_square(): - raise ValueError, "D must not be a perfect square." + raise ValueError("D must not be a perfect square.") R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: @@ -902,7 +902,7 @@ def CyclotomicField(n=0, names=None, bracket="()", embedding=True): from sage.rings.universal_cyclotomic_field.universal_cyclotomic_field import UniversalCyclotomicField return UniversalCyclotomicField(names=names, bracket=bracket, embedding=embedding) if n < 0: - raise ValueError, "n (=%s) must be a positive integer"%n + raise ValueError("n (=%s) must be a positive integer"%n) if names is None: names = "zeta%s"%n @@ -1018,15 +1018,15 @@ def __init__(self, polynomial, name, ParentWithGens.__init__(self, QQ, name, category=category) if not isinstance(polynomial, polynomial_element.Polynomial): - raise TypeError, "polynomial (=%s) must be a polynomial"%repr(polynomial) + raise TypeError("polynomial (=%s) must be a polynomial"%repr(polynomial)) if check: if not polynomial.parent().base_ring() == QQ: - raise TypeError, "polynomial must be defined over rational field" + raise TypeError("polynomial must be defined over rational field") if not polynomial.is_monic(): - raise NotImplementedError, "number fields for non-monic polynomials not yet implemented." + raise NotImplementedError("number fields for non-monic polynomials not yet implemented.") if not polynomial.is_irreducible(): - raise ValueError, "defining polynomial (%s) must be irreducible"%polynomial + raise ValueError("defining polynomial (%s) must be irreducible"%polynomial) self._assign_names(name) if latex_name is None: @@ -1238,7 +1238,7 @@ def _element_constructor_(self, x): (isinstance(x, sage.modules.free_module_element.FreeModuleElement) and self.base_ring().has_coerce_map_from(x.parent().base_ring())): if len(x) != self.relative_degree(): - raise ValueError, "Length must be equal to the degree of this number field" + raise ValueError("Length must be equal to the degree of this number field") result = x[0] for i in xrange(1,self.relative_degree()): result += x[i]*self.gen(0)**i @@ -1383,7 +1383,7 @@ def _set_structure(self, from_self, to_self, unsafe_force_change=False): self.__from_self = from_self self.__to_self = to_self else: - raise ValueError, "number field structure is immutable." + raise ValueError("number field structure is immutable.") def structure(self): """ @@ -1446,7 +1446,7 @@ def completion(self, p, prec, extras={}): return QQ.completion(p, prec, extras) elif gen_image in CDF: return QQ.completion(p, prec, extras).algebraic_closure() - raise ValueError, "No embedding into the complex numbers has been specified." + raise ValueError("No embedding into the complex numbers has been specified.") else: raise NotImplementedError @@ -1694,7 +1694,7 @@ def change_generator(self, alpha, name=None, names=None): alpha = self(alpha) K, from_K = self.subfield(alpha, name=name) if K.degree() != self.degree(): - raise ValueError, "alpha must generate a field of degree %s, but alpha generates a subfield of degree %s"%(self.degree(), K.degree()) + raise ValueError("alpha must generate a field of degree %s, but alpha generates a subfield of degree %s"%(self.degree(), K.degree())) # Now compute to_K, which is an isomorphism # from self to K such that from_K(to_K(x)) == x for all x, # and to_K(from_K(y)) == y. @@ -1790,7 +1790,7 @@ def is_isomorphic(self, other): False """ if not isinstance(other, NumberField_generic): - raise ValueError, "other must be a generic number field." + raise ValueError("other must be a generic number field.") t = self.pari_polynomial().nfisisom(other.pari_polynomial()) return t != 0 @@ -2864,7 +2864,7 @@ def prime_above(self, x, degree=None): """ ids = self.primes_above(x, degree) if not ids: - raise ValueError, "No prime of degree %s above %s" % (degree, self.ideal(x)) + raise ValueError("No prime of degree %s above %s" % (degree, self.ideal(x))) return ids[0] def primes_of_degree_one_iter(self, num_integer_primes=10000, max_iterations=100): @@ -3095,7 +3095,7 @@ def pari_nf(self, important=True): [y^2 - 100000000000000000000...] """ if self.absolute_polynomial().denominator() != 1: - raise TypeError, "Unable to coerce number field defined by non-integral polynomial to PARI." + raise TypeError("Unable to coerce number field defined by non-integral polynomial to PARI.") try: return self.__pari_nf except AttributeError: @@ -3196,7 +3196,7 @@ def pari_bnf(self, proof=None, units=True): bnf = self.__pari_bnf except AttributeError: if self.absolute_polynomial().denominator() != 1: - raise TypeError, "Unable to coerce number field defined by non-integral polynomial to PARI." + raise TypeError("Unable to coerce number field defined by non-integral polynomial to PARI.") f = self.pari_polynomial("y") if units: self.__pari_bnf = f.bnfinit(1) @@ -3206,7 +3206,7 @@ def pari_bnf(self, proof=None, units=True): # Certify if needed if proof and not getattr(self, "__pari_bnf_certified", False): if bnf.bnfcertify() != 1: - raise ValueError, "The result is not correct according to bnfcertify" + raise ValueError("The result is not correct according to bnfcertify") self.__pari_bnf_certified = True return bnf @@ -3230,7 +3230,7 @@ def pari_rnfnorm_data(self, L, proof=True): 8 """ if L.base_field() != self: - raise ValueError, "L must be an extension of self" + raise ValueError("L must be an extension of self") relpoly = L.defining_polynomial() Kbnf = self.pari_bnf(proof=proof) @@ -3268,7 +3268,7 @@ def _gap_init_(self): """ if not self.is_absolute(): - raise NotImplementedError, "Currently, only simple algebraic extensions are implemented in gap" + raise NotImplementedError("Currently, only simple algebraic extensions are implemented in gap") G = sage.interfaces.gap.gap q = self.polynomial() if q.variable_name()!='E': @@ -3797,7 +3797,7 @@ def composite_fields(self, other, names=None, both_maps=False, preserve_embeddin b |--> b, None)] """ if not isinstance(other, NumberField_generic): - raise TypeError, "other must be a number field." + raise TypeError("other must be a number field.") sv = self.variable_name(); ov = other.variable_name() if names is None: @@ -4089,10 +4089,10 @@ def trace_dual_basis(self, b): [1, 0, 0, 0, 1, 0, 0, 0, 1] """ if not len(b) == self.degree(): - raise ValueError, 'Not a basis of the number field.' + raise ValueError('Not a basis of the number field.') M = self.trace_pairing(b) if not M.is_invertible(): - raise ValueError, 'Not a basis of the number field.' + raise ValueError('Not a basis of the number field.') return [sum([v[i]*b[i] for i in xrange(len(b))]) for v in M.inverse()] def elements_of_norm(self, n, proof=None): @@ -4157,13 +4157,13 @@ def extension(self, poly, name=None, names=None, check=True, embedding=None): try: poly = poly.polynomial(self) except (AttributeError, TypeError): - raise TypeError, "polynomial (=%s) must be a polynomial."%repr(poly) + raise TypeError("polynomial (=%s) must be a polynomial."%repr(poly)) if not names is None: name = names if isinstance(name, tuple): name = name[0] if name is None: - raise TypeError, "the variable name must be specified." + raise TypeError("the variable name must be specified.") from sage.rings.number_field.number_field_rel import NumberField_relative return NumberField_relative(self, poly, str(name), check=check, embedding=embedding) @@ -4268,7 +4268,7 @@ def gen(self, n=0): IndexError: Only one generator. """ if n != 0: - raise IndexError, "Only one generator." + raise IndexError("Only one generator.") try: return self.__gen except AttributeError: @@ -4409,7 +4409,7 @@ def galois_group(self, type=None, algorithm='pari', names=None): elif type=="gap": return GaloisGroup_v1(self.absolute_polynomial().galois_group(pari_group=False, algorithm=algorithm), self) else: - raise ValueError, "Galois group type must be None, 'pari', or 'gap'." + raise ValueError("Galois group type must be None, 'pari', or 'gap'.") def _normalize_prime_list(self, v): """ @@ -4553,7 +4553,7 @@ def _pari_integral_basis(self, v=None, important=True): if all([ p < trialdivlimit2 or (e == 1 and p < trialdivlimit3) or p.isprime() for p,e in zip(m[0],m[1]) ]): B = f.nfbasis(fa = m) else: - raise RuntimeError, "Unable to factor discriminant with trial division" + raise RuntimeError("Unable to factor discriminant with trial division") else: B = f.nfbasis() @@ -4796,10 +4796,10 @@ def _positive_integral_elements_with_trace(self, C): ValueError: bounds must be positive """ if C[0] < 0: - raise ValueError, "bounds must be positive" + raise ValueError("bounds must be positive") if not self.is_totally_real(): - raise NotImplementedError, "exact computation of LLL reduction only implemented in the totally real case" + raise NotImplementedError("exact computation of LLL reduction only implemented in the totally real case") Z_F = self.maximal_order() B = self.reduced_basis() @@ -5120,7 +5120,7 @@ def residue_field(self, prime, names=None, check=True): """ from sage.rings.number_field.number_field_ideal import is_NumberFieldIdeal if is_NumberFieldIdeal(prime) and prime.number_field() is not self: - raise ValueError, "%s is not an ideal of %s"%(prime,self) + raise ValueError("%s is not an ideal of %s"%(prime,self)) # This allows principal ideals to be specified using a generator: try: prime = self.ideal(prime) @@ -5128,9 +5128,9 @@ def residue_field(self, prime, names=None, check=True): pass if not is_NumberFieldIdeal(prime) or prime.number_field() is not self: - raise ValueError, "%s is not an ideal of %s"%(prime,self) + raise ValueError("%s is not an ideal of %s"%(prime,self)) if check and not prime.is_prime(): - raise ValueError, "%s is not a prime ideal"%prime + raise ValueError("%s is not a prime ideal"%prime) from sage.rings.residue_field import ResidueField return ResidueField(prime, names=names, check=False) @@ -5573,7 +5573,7 @@ def zeta(self, n=2, all=False): K = self n = ZZ(n) if n <= 0: - raise ValueError, "n (=%s) must be positive"%n + raise ValueError("n (=%s) must be positive"%n) if n == 1: if all: return [K(1)] @@ -5595,7 +5595,7 @@ def zeta(self, n=2, all=False): if all: return [] else: - raise ValueError, "There are no %s roots of unity in self."%n.ordinal_str() + raise ValueError("There are no %s roots of unity in self."%n.ordinal_str()) def zeta_order(self): r""" @@ -5926,13 +5926,13 @@ def _coerce_from_other_number_field(self, x): F = LF Kgen = F(Kgen) else: - raise TypeError, "No compatible natural embeddings found for %s and %s"%(KF,LF) + raise TypeError("No compatible natural embeddings found for %s and %s"%(KF,LF)) # List of candidates for K(x) f = x.minpoly() ys = f.roots(ring=K, multiplicities=False) if not ys: - raise ValueError, "Cannot convert %s to %s (regardless of embeddings)"%(x,K) + raise ValueError("Cannot convert %s to %s (regardless of embeddings)"%(x,K)) # Define a function are_roots_equal to determine whether two # roots of f are equal. A simple a == b does not suffice for @@ -5989,7 +5989,7 @@ def _coerce_from_other_number_field(self, x): emb_y = y.polynomial()(Kgen) if are_roots_equal(emb_x, emb_y): return y - raise ValueError, "Cannot convert %s to %s (using the specified embeddings)"%(x,K) + raise ValueError("Cannot convert %s to %s (using the specified embeddings)"%(x,K)) def _coerce_non_number_field_element_in(self, x): """ @@ -6050,7 +6050,7 @@ def _coerce_non_number_field_element_in(self, x): return self._element_class(self, x._rational_()) except (TypeError, AttributeError) as msg: pass - raise TypeError, type(x) + raise TypeError(type(x)) def _coerce_from_str(self, x): r""" @@ -7353,7 +7353,7 @@ def relativize(self, alpha, names): if is_Map(alpha): # alpha better be a morphism with codomain self if alpha.codomain() != self: - raise ValueError, "Co-domain of morphism must be self" + raise ValueError("Co-domain of morphism must be self") L = alpha.domain() alpha = alpha(L.gen()) # relativize over phi's domain f = L.defining_polynomial() # = alpha.minpoly() @@ -7734,7 +7734,7 @@ def hilbert_symbol(self, a, b, P = None): from sage.rings.morphism import is_RingHomomorphism if is_RingHomomorphism(P): if not P.domain() == self: - raise ValueError, "Domain of P (=%s) should be self (=%s) in self.hilbert_symbol" % (P, self) + raise ValueError("Domain of P (=%s) should be self (=%s) in self.hilbert_symbol" % (P, self)) codom = P.codomain() from sage.rings.complex_field import is_ComplexField from sage.rings.complex_interval_field import is_ComplexIntervalField @@ -7744,7 +7744,7 @@ def hilbert_symbol(self, a, b, P = None): if is_ComplexField(codom) or is_ComplexIntervalField(codom) or \ codom is CDF or codom is QQbar: if P(self.gen()).imag() == 0: - raise ValueError, "Possibly real place (=%s) given as complex embedding in hilbert_symbol. Is it real or complex?" % P + raise ValueError("Possibly real place (=%s) given as complex embedding in hilbert_symbol. Is it real or complex?" % P) return 1 if is_RealField(codom) or codom is RDF or codom is AA: if P(a) > 0 or P(b) > 0: @@ -7753,9 +7753,9 @@ def hilbert_symbol(self, a, b, P = None): if not is_NumberFieldIdeal(P): P = self.ideal(P) if not P.number_field() == self: - raise ValueError, "P (=%s) should be an ideal of self (=%s) in hilbert_symbol, not of %s" % (P, self, P.number_field()) + raise ValueError("P (=%s) should be an ideal of self (=%s) in hilbert_symbol, not of %s" % (P, self, P.number_field())) if not P.is_prime(): - raise ValueError, "Non-prime ideal P (=%s) in hilbert_symbol" % P + raise ValueError("Non-prime ideal P (=%s) in hilbert_symbol" % P) return pari(self).nfhilbert(a, b, P.pari_prime()) def hilbert_conductor(self,a,b): @@ -8476,7 +8476,7 @@ def _coerce_from_other_cyclotomic_field(self, x, only_canonical=False): if z == x: return self.zeta(m)**(r+1) z *= y - raise TypeError, "Cannot coerce %s into %s"%(x,self) + raise TypeError("Cannot coerce %s into %s"%(x,self)) return self._element_class(self, g) @@ -8990,7 +8990,7 @@ def zeta(self, n=None, all=False): z = -z**((m+1)//2) # -z m = 2*m if m % n != 0: - raise ValueError, "n (=%s) does not divide order of generator"%n + raise ValueError("n (=%s) does not divide order of generator"%n) # use generic method (factor cyclotomic polynomial) # -- this is potentially really slow, so don't do it. #return field.Field.zeta(self, n, all=all) @@ -9368,7 +9368,7 @@ def hilbert_class_polynomial(self, name='x'): D = self.discriminant() if D > 0: - raise NotImplementedError, "Hilbert class polynomial is not implemented for real quadratic fields." + raise NotImplementedError("Hilbert class polynomial is not implemented for real quadratic fields.") from sage.schemes.elliptic_curves.all import hilbert_class_polynomial as HCP return QQ[name](HCP(D)) diff --git a/src/sage/rings/number_field/number_field_ideal.py b/src/sage/rings/number_field/number_field_ideal.py index ea09cde8714..ccc77e1b2ab 100644 --- a/src/sage/rings/number_field/number_field_ideal.py +++ b/src/sage/rings/number_field/number_field_ideal.py @@ -168,7 +168,7 @@ def __init__(self, field, gens, coerce=True): [5, [-2, 1]~, 1, 1, [2, 1]~] """ if not isinstance(field, number_field.NumberField_generic): - raise TypeError, "field (=%s) must be a number field."%field + raise TypeError("field (=%s) must be a number field."%field) if len(gens) == 1 and isinstance(gens[0], (list, tuple)): gens = gens[0] @@ -187,7 +187,7 @@ def __init__(self, field, gens, coerce=True): # Assume one element of the field gens = [field(gens)] if len(gens)==0: - raise ValueError, "gens must have length at least 1 (zero ideal is not a fractional ideal)" + raise ValueError("gens must have length at least 1 (zero ideal is not a fractional ideal)") Ideal_generic.__init__(self, field, gens, coerce) def __hash__(self): @@ -1067,7 +1067,7 @@ def pari_prime(self): ValueError: Fractional ideal (2) is not a prime ideal """ if not self.is_prime(): - raise ValueError, "%s is not a prime ideal"%self + raise ValueError("%s is not a prime ideal"%self) return self._pari_prime def _cache_bnfisprincipal(self, proof=None, gens_needed=False): @@ -1433,13 +1433,13 @@ def valuation(self, p): ValueError: p (= 0) must be nonzero """ if p==0: - raise ValueError, "p (= %s) must be nonzero"%p + raise ValueError("p (= %s) must be nonzero"%p) if not isinstance(p, NumberFieldFractionalIdeal): p = self.number_field().ideal(p) if not p.is_prime(): - raise ValueError, "p (= %s) must be a prime"%p + raise ValueError("p (= %s) must be a prime"%p) if p.ring() != self.number_field(): - raise ValueError, "p (= %s) must be an ideal in %s"%self.number_field() + raise ValueError("p (= %s) must be an ideal in %s"%self.number_field()) nf = self.number_field().pari_nf() return ZZ(nf.idealval(self.pari_hnf(), p.pari_prime())) @@ -1617,25 +1617,25 @@ def residue_symbol(self, e, m, check=True): return kronecker_symbol(ze, zp) if check: if self.is_trivial(): - raise ValueError, "Ideal must be proper" + raise ValueError("Ideal must be proper") if m < 1: - raise ValueError, "Power must be positive" + raise ValueError("Power must be positive") if not self.is_coprime(e): - raise ValueError, "Element is not coprime to the ideal" + raise ValueError("Element is not coprime to the ideal") if not self.is_coprime(m): - raise ValueError, "Ideal is not coprime to the power" + raise ValueError("Ideal is not coprime to the power") primroot = K.primitive_root_of_unity() rootorder = primroot.multiplicative_order() if check: if not rootorder%m == 0: - raise ValueError, "The residue symbol to that power is not defined for the number field" + raise ValueError("The residue symbol to that power is not defined for the number field") if not self.is_prime(): return prod(Q.residue_symbol(e,m,check=False)**i for Q, i in self.factor()) k = self.residue_field() try: r = k(e) except TypeError: - raise ValueError, "Element and ideal must be in a common number field" + raise ValueError("Element and ideal must be in a common number field") r = k(r**((k.order()-1)/m)) resroot = primroot**(rootorder/m) from sage.groups.generic import discrete_log @@ -1703,16 +1703,16 @@ def __init__(self, field, gens, coerce=True): Fractional ideal (7) """ if not isinstance(field, number_field.NumberField_generic): - raise TypeError, "field (=%s) must be a number field."%field + raise TypeError("field (=%s) must be a number field."%field) if len(gens)==0: - raise ValueError, "gens must have length at least 1 (zero ideal is not a fractional ideal)" + raise ValueError("gens must have length at least 1 (zero ideal is not a fractional ideal)") if len(gens) == 1 and isinstance(gens[0], (list, tuple)): gens = gens[0] if misc.exists(gens,bool)[0]: NumberFieldIdeal.__init__(self, field, gens) else: - raise ValueError, "gens must have a nonzero element (zero ideal is not a fractional ideal)" + raise ValueError("gens must have a nonzero element (zero ideal is not a fractional ideal)") def __repr__(self): """ @@ -1992,12 +1992,12 @@ def reduce(self, f): """ if not self.is_integral(): - raise ValueError, "reduce only defined for integral ideals" + raise ValueError("reduce only defined for integral ideals") R = self.number_field().maximal_order() if not (f in R): - raise TypeError, "reduce only defined for integral elements" + raise TypeError("reduce only defined for integral elements") Rbasis = R.basis() n = len(Rbasis) @@ -2065,7 +2065,7 @@ def residues(self): True """ if not self.is_integral(): - raise ValueError, "residues only defined for integral ideals" + raise ValueError("residues only defined for integral ideals") R = self.number_field().maximal_order() Rbasis = R.basis() @@ -2380,7 +2380,7 @@ def idealcoprime(self, J): ALGORITHM: Uses Pari function ``idealcoprime``. """ if not (self.is_integral() and J.is_integral()): - raise ValueError, "Both ideals must be integral." + raise ValueError("Both ideals must be integral.") k = self.number_field() # Catch invalid inputs by making sure that J is an ideal of the same field as self: @@ -2418,7 +2418,7 @@ def small_residue(self, f): """ if not self.is_integral(): - raise ValueError, "The ideal must be integral" + raise ValueError("The ideal must be integral") k = self.number_field() return k(k.pari_nf().nfeltreduce(f._pari_(), self.pari_hnf())) @@ -2603,7 +2603,7 @@ def ideallog(self, x, gens=None, check=True): k = self.number_field() if not all([k(x).valuation(p)==0 for p, e in self.factor()]): - raise TypeError, "the element must be invertible mod the ideal" + raise TypeError("the element must be invertible mod the ideal") # calculate ideal log w.r.t. standard gens @@ -2633,7 +2633,7 @@ def ideallog(self, x, gens=None, check=True): hmat = mat.hermite_form() A = hmat[0:len(invs), 0:len(invs)] if A != identity_matrix(len(invs)): - raise ValueError, "Given elements do not generate unit group -- they generate a subgroup of index %s" % A.det() + raise ValueError("Given elements do not generate unit group -- they generate a subgroup of index %s" % A.det()) B = hmat[0:len(invs), len(invs):] C = hmat[len(invs):, len(invs):] #print "Matrix of relations:\n%s" % C @@ -2704,16 +2704,16 @@ def element_1_mod(self, other): TypeError: Fractional ideal (1/2*a^2) is not an integral ideal """ if not self.is_integral(): - raise TypeError, "%s is not an integral ideal"%self + raise TypeError("%s is not an integral ideal"%self) # Catch invalid inputs by making sure that we can make an ideal out of other. K = self.number_field() other = K.ideal(other) if not other.is_integral(): - raise TypeError, "%s is not an integral ideal"%other + raise TypeError("%s is not an integral ideal"%other) if not self.is_coprime(other): - raise TypeError, "%s, %s are not coprime ideals"%(self, other) + raise TypeError("%s, %s are not coprime ideals"%(self, other)) bnf = K.pari_bnf() r = bnf.idealaddtoone(self.pari_hnf(), other.pari_hnf())[0] @@ -2751,7 +2751,7 @@ def euler_phi(self): 64 """ if not self.is_integral(): - raise ValueError, "euler_phi only defined for integral ideals" + raise ValueError("euler_phi only defined for integral ideals") return prod([(np-1)*np**(e-1) \ for np,e in [(p.absolute_norm(),e) \ for p,e in self.factor()]]) @@ -2902,7 +2902,7 @@ def prime_to_idealM_part(self, M): M = k.ideal(M) if not self.is_integral or not M.is_integral(): - raise TypeError, "prime_to_idealM_part defined only for integral ideals" + raise TypeError("prime_to_idealM_part defined only for integral ideals") if self.is_coprime(M): return self @@ -3042,7 +3042,7 @@ def residue_field(self, names=None): Residue field in abar of Fractional ideal (a) """ if not self.is_prime(): - raise ValueError, "The ideal must be prime" + raise ValueError("The ideal must be prime") return self.number_field().residue_field(self, names = names) def residue_class_degree(self): @@ -3267,7 +3267,7 @@ def quotient_char_p(I, p): [1 8] """ if not I.is_integral(): - raise ValueError, "I must be an integral ideal." + raise ValueError("I must be an integral ideal.") K = I.number_field() OK = K.maximal_order() # will in the long run only really need a p-maximal order. diff --git a/src/sage/rings/number_field/number_field_ideal_rel.py b/src/sage/rings/number_field/number_field_ideal_rel.py index 0c7aba58dc8..ba6fab5287a 100644 --- a/src/sage/rings/number_field/number_field_ideal_rel.py +++ b/src/sage/rings/number_field/number_field_ideal_rel.py @@ -403,7 +403,7 @@ def norm(self): ... NotImplementedError: For a fractional ideal in a relative number field you must use relative_norm or absolute_norm as appropriate """ - raise NotImplementedError, "For a fractional ideal in a relative number field you must use relative_norm or absolute_norm as appropriate" + raise NotImplementedError("For a fractional ideal in a relative number field you must use relative_norm or absolute_norm as appropriate") def ideal_below(self): r""" @@ -638,7 +638,7 @@ def absolute_ramification_index(self): """ if self.is_prime(): return self.absolute_ideal().ramification_index() - raise ValueError, "the fractional ideal (= %s) is not prime"%self + raise ValueError("the fractional ideal (= %s) is not prime"%self) def relative_ramification_index(self): """ @@ -673,7 +673,7 @@ def relative_ramification_index(self): abs_index = self.absolute_ramification_index() base_ideal = self.ideal_below() return ZZ(abs_index/base_ideal.absolute_ramification_index()) - raise ValueError, "the fractional ideal (= %s) is not prime"%self + raise ValueError("the fractional ideal (= %s) is not prime"%self) def ramification_index(self): r""" @@ -690,7 +690,7 @@ def ramification_index(self): ... NotImplementedError: For an ideal in a relative number field you must use relative_ramification_index or absolute_ramification_index as appropriate """ - raise NotImplementedError, "For an ideal in a relative number field you must use relative_ramification_index or absolute_ramification_index as appropriate" + raise NotImplementedError("For an ideal in a relative number field you must use relative_ramification_index or absolute_ramification_index as appropriate") def residue_class_degree(self): r""" @@ -707,7 +707,7 @@ def residue_class_degree(self): """ if self.is_prime(): return self.absolute_ideal().residue_class_degree() - raise ValueError, "the ideal (= %s) is not prime"%self + raise ValueError("the ideal (= %s) is not prime"%self) def residues(self): """ @@ -762,14 +762,14 @@ def element_1_mod(self, other): # Catch invalid inputs by making sure that we can make an ideal out of other. K = self.number_field() if not self.is_integral(): - raise TypeError, "%s is not an integral ideal"%self + raise TypeError("%s is not an integral ideal"%self) other = K.ideal(other) if not other.is_integral(): - raise TypeError, "%s is not an integral ideal"%other + raise TypeError("%s is not an integral ideal"%other) if not self.is_coprime(other): - raise TypeError, "%s and %s are not coprime ideals"%(self, other) + raise TypeError("%s and %s are not coprime ideals"%(self, other)) to_K = K.absolute_field('a').structure()[0] return to_K(self.absolute_ideal().element_1_mod(other.absolute_ideal())) @@ -819,13 +819,13 @@ def valuation(self, p): ValueError: p (= Fractional ideal (5)) must be a prime """ if p == 0: - raise ValueError, "p (= %s) must be nonzero"%p + raise ValueError("p (= %s) must be nonzero"%p) if not isinstance(p, NumberFieldFractionalIdeal): p = self.number_field().ideal(p) if not p.is_prime(): - raise ValueError, "p (= %s) must be a prime"%p + raise ValueError("p (= %s) must be a prime"%p) if p.ring() != self.number_field(): - raise ValueError, "p (= %s) must be an ideal in %s"%self.number_field() + raise ValueError("p (= %s) must be an ideal in %s"%self.number_field()) return self.absolute_ideal().valuation(p.absolute_ideal()) def is_NumberFieldFractionalIdeal_rel(x): diff --git a/src/sage/rings/number_field/number_field_rel.py b/src/sage/rings/number_field/number_field_rel.py index 79f444de5a2..b2a4a757913 100644 --- a/src/sage/rings/number_field/number_field_rel.py +++ b/src/sage/rings/number_field/number_field_rel.py @@ -243,22 +243,22 @@ def __init__(self, base, polynomial, name, ValueError: defining polynomial (x^2 + 2) must be irreducible """ if embedding is not None: - raise NotImplementedError, "Embeddings not implemented for relative number fields" + raise NotImplementedError("Embeddings not implemented for relative number fields") if not names is None: name = names if not is_NumberField(base): - raise TypeError, "base (=%s) must be a number field"%base + raise TypeError("base (=%s) must be a number field"%base) if not isinstance(polynomial, polynomial_element.Polynomial): try: polynomial = polynomial.polynomial(base) except (AttributeError, TypeError) as msg: - raise TypeError, "polynomial (=%s) must be a polynomial."%repr(polynomial) + raise TypeError("polynomial (=%s) must be a polynomial."%repr(polynomial)) if name == base.variable_name(): - raise ValueError, "Base field and extension cannot have the same name" + raise ValueError("Base field and extension cannot have the same name") if polynomial.parent().base_ring() != base: polynomial = polynomial.change_ring(base) #raise ValueError, "The polynomial must be defined over the base field" if not polynomial.is_monic(): - raise NotImplementedError, "Number fields for non-monic polynomials not yet implemented." + raise NotImplementedError("Number fields for non-monic polynomials not yet implemented.") # Generate the nf and bnf corresponding to the base field # defined as polynomials in y, e.g. for rnfisfree @@ -280,7 +280,7 @@ def __init__(self, base, polynomial, name, self._element_class = number_field_element.NumberFieldElement_relative if check and not self.pari_relative_polynomial().polisirreducible(): - raise ValueError, "defining polynomial (%s) must be irreducible"%polynomial + raise ValueError("defining polynomial (%s) must be irreducible"%polynomial) self.__gens = [None] @@ -497,7 +497,7 @@ def gen(self, n=0): a """ if n < 0 or n >= len(self.__gens): - raise IndexError, "invalid generator %s"%n + raise IndexError("invalid generator %s"%n) return self.__gens[n] def galois_closure(self, names=None): @@ -564,7 +564,7 @@ def composite_fields(self, other, names=None, both_maps=False, preserve_embeddin None]] """ if not isinstance(other, NumberField_generic): - raise TypeError, "other must be a number field." + raise TypeError("other must be a number field.") if names is None: sv = self.variable_name(); ov = other.variable_name() names = sv + (ov if ov != sv else "") @@ -635,7 +635,7 @@ def degree(self): ... NotImplementedError: For a relative number field you must use relative_degree or absolute_degree as appropriate """ - raise NotImplementedError, "For a relative number field you must use relative_degree or absolute_degree as appropriate" + raise NotImplementedError("For a relative number field you must use relative_degree or absolute_degree as appropriate") def maximal_order(self, v=None): """ @@ -794,7 +794,7 @@ def _coerce_from_other_number_field(self, x): if f.degree() <= 0: return self._element_class(self, f[0]) # todo: more general coercion if embedding have been asserted - raise TypeError, "Cannot coerce element into this number field" + raise TypeError("Cannot coerce element into this number field") def _coerce_non_number_field_element_in(self, x): r""" @@ -1001,7 +1001,7 @@ def _coerce_non_number_field_element_in(self, x): return self._element_class(self, x._rational_()) except AttributeError: pass - raise TypeError, type(x) + raise TypeError(type(x)) def _coerce_map_from_(self, R): """ @@ -1184,7 +1184,7 @@ def is_galois(self): ... NotImplementedError: For a relative number field L you must use either L.is_galois_relative() or L.is_galois_absolute() as appropriate """ - raise NotImplementedError, "For a relative number field L you must use either L.is_galois_relative() or L.is_galois_absolute() as appropriate" + raise NotImplementedError("For a relative number field L you must use either L.is_galois_relative() or L.is_galois_absolute() as appropriate") def is_galois_relative(self): r""" @@ -1449,7 +1449,7 @@ def vector_space(self): NotImplementedError: For a relative number field L you must use either L.relative_vector_space() or L.absolute_vector_space() as appropriate """ - raise NotImplementedError, "For a relative number field L you must use either L.relative_vector_space() or L.absolute_vector_space() as appropriate" + raise NotImplementedError("For a relative number field L you must use either L.relative_vector_space() or L.absolute_vector_space() as appropriate") def absolute_base_field(self): r""" @@ -1832,7 +1832,7 @@ def polynomial(self): ... NotImplementedError: For a relative number field L you must use either L.relative_polynomial() or L.absolute_polynomial() as appropriate """ - raise NotImplementedError, "For a relative number field L you must use either L.relative_polynomial() or L.absolute_polynomial() as appropriate" + raise NotImplementedError("For a relative number field L you must use either L.relative_polynomial() or L.absolute_polynomial() as appropriate") def base_field(self): """ @@ -2098,7 +2098,7 @@ def different(self): ... NotImplementedError: For a relative number field you must use relative_different or absolute_different as appropriate """ - raise NotImplementedError, "For a relative number field you must use relative_different or absolute_different as appropriate" + raise NotImplementedError("For a relative number field you must use relative_different or absolute_different as appropriate") def absolute_discriminant(self, v=None): r""" @@ -2171,7 +2171,7 @@ def discriminant(self): ... NotImplementedError: For a relative number field you must use relative_discriminant or absolute_discriminant as appropriate """ - raise NotImplementedError, "For a relative number field you must use relative_discriminant or absolute_discriminant as appropriate" + raise NotImplementedError("For a relative number field you must use relative_discriminant or absolute_discriminant as appropriate") def disc(self): """ @@ -2187,7 +2187,7 @@ def disc(self): ... NotImplementedError: For a relative number field you must use relative_discriminant or absolute_discriminant as appropriate """ - raise NotImplementedError, "For a relative number field you must use relative_discriminant or absolute_discriminant as appropriate" + raise NotImplementedError("For a relative number field you must use relative_discriminant or absolute_discriminant as appropriate") def order(self, *gens, **kwds): """ @@ -2267,7 +2267,7 @@ def galois_group(self, type = 'pari', algorithm='pari', names=None): """ if type is None: - raise NotImplementedError, "Galois groups of relative extensions not implemented (use the corresponding absolute field)" + raise NotImplementedError("Galois groups of relative extensions not implemented (use the corresponding absolute field)") else: # silly bug in cached_method return NumberField_generic.galois_group.f(self, type, algorithm, names) @@ -2333,7 +2333,7 @@ def lift_to_base(self, element): # Now we should have a polynomial in the variable y. # Otherwise we're not in the base field. if r.type() != "t_POL" or str(r.variable()) != 'y': - raise ValueError, "The element %s is not in the base field"%element + raise ValueError("The element %s is not in the base field"%element) return self.base_field()(r) def relativize(self, alpha, names): @@ -2483,7 +2483,7 @@ def uniformizer(self, P, others = "positive"): if not is_NumberFieldIdeal(P): P = self.ideal(P) if not P.is_maximal(): - raise ValueError, "P (=%s) must be a nonzero prime."%P + raise ValueError("P (=%s) must be a nonzero prime."%P) abs = self.absolute_field('a') from_abs = abs.structure()[0] return from_abs(abs.uniformizer(P.absolute_ideal(), others=others)) diff --git a/src/sage/rings/number_field/order.py b/src/sage/rings/number_field/order.py index 767d27186ba..99fe0158f10 100644 --- a/src/sage/rings/number_field/order.py +++ b/src/sage/rings/number_field/order.py @@ -105,12 +105,12 @@ def EquationOrder(f, names): try: R(g) except TypeError: - raise ValueError, 'each generator must be integral' + raise ValueError('each generator must be integral') else: try: R(f) except TypeError: - raise ValueError, 'each generator must be integral' + raise ValueError('each generator must be integral') K = NumberField(f, names=names) return K.order(K.gens()) @@ -216,10 +216,10 @@ def ideal(self, *args, **kwds): Ideal (0) of Number Field in a with defining polynomial x^2 + 2 """ if not self.is_maximal(): - raise NotImplementedError, "ideals of non-maximal orders not yet supported." + raise NotImplementedError("ideals of non-maximal orders not yet supported.") I = self.number_field().ideal(*args, **kwds) if not I.is_integral(): - raise ValueError, "ideal must be integral; use fractional_ideal to create a non-integral ideal." + raise ValueError("ideal must be integral; use fractional_ideal to create a non-integral ideal.") return I def _coerce_map_from_(self, R): @@ -418,7 +418,7 @@ def gen(self, i): """ b = self.basis() if i < 0 or i >= len(b): - raise IndexError, "no %sth generator"%i + raise IndexError("no %sth generator"%i) return self.basis()[i] def gens(self): @@ -637,7 +637,7 @@ def zeta(self, n=2, all=False): if all: return [] else: - raise ArithmeticError, "There are no %s roots of unity in self."%n.ordinal_str() + raise ArithmeticError("There are no %s roots of unity in self."%n.ordinal_str()) if all: return roots_in_self else: @@ -709,7 +709,7 @@ def residue_field(self, prime, name = None, check = False): if self.is_maximal(): return self.number_field().residue_field(prime, name, check) else: - raise NotImplementedError, "Residue fields of non-maximal orders are not yet supported." + raise NotImplementedError("Residue fields of non-maximal orders are not yet supported.") def fraction_field(self): """ @@ -779,7 +779,7 @@ def class_number(self, proof=None): NotImplementedError: computation of class numbers of non-maximal orders is not implemented """ if not self.is_maximal(): - raise NotImplementedError, "computation of class numbers of non-maximal orders is not implemented" + raise NotImplementedError("computation of class numbers of non-maximal orders is not implemented") return self.number_field().class_number(proof=proof) def class_group(self, proof=None, names='c'): @@ -1041,11 +1041,11 @@ def __init__(self, K, module_rep, is_maximal=None, check=True): V, from_v, to_v = self._K.vector_space() if check: if not K.is_absolute(): - raise ValueError, "AbsoluteOrder must be called with an absolute number field." + raise ValueError("AbsoluteOrder must be called with an absolute number field.") if to_v(1) not in module_rep: - raise ValueError, "1 is not in the span of the module, hence not an order." + raise ValueError("1 is not in the span of the module, hence not an order.") if module_rep.rank() != self._K.degree(): - raise ValueError, "the module must have full rank." + raise ValueError("the module must have full rank.") def _element_constructor_(self, x): r""" @@ -1067,7 +1067,7 @@ def _element_constructor_(self, x): x = self._K(x) V, _, embedding = self._K.vector_space() if not embedding(x) in self._module_rep: - raise TypeError, "Not an element of the order." + raise TypeError("Not an element of the order.") return self._element_type(self, x) def __reduce__(self): @@ -1109,7 +1109,7 @@ def __add__(left, right): if not isinstance(left, AbsoluteOrder) or not isinstance(right, AbsoluteOrder): raise NotImplementedError if left.number_field() != right.number_field(): - raise TypeError, "Number fields don't match." + raise TypeError("Number fields don't match.") if left._is_maximal: return left elif right._is_maximal: @@ -1134,7 +1134,7 @@ def __and__(left, right): if not isinstance(left, AbsoluteOrder) or not isinstance(right, AbsoluteOrder): raise NotImplementedError if left.number_field() != right.number_field(): - raise TypeError, "Number fields don't match." + raise TypeError("Number fields don't match.") return AbsoluteOrder(left._K, left._module_rep.intersection(right._module_rep), False) def _magma_init_(self, magma): @@ -1254,9 +1254,9 @@ def index_in(self, other): 1/16 """ if not isinstance(other, AbsoluteOrder): - raise TypeError, "other must be an absolute order." + raise TypeError("other must be an absolute order.") if other.ambient() != self.ambient(): - raise ValueError, "other must have the same ambient number field as self." + raise ValueError("other must have the same ambient number field as self.") return self._module_rep.index_in(other._module_rep) def module(self): @@ -1566,7 +1566,7 @@ def __add__(left, right): return left._absolute_order + right elif isinstance(left, RelativeOrder) and isinstance(right, RelativeOrder): if left._K != right._K: - raise TypeError, "Number fields don't match." + raise TypeError("Number fields don't match.") return RelativeOrder(left._K, left._absolute_order + right._absolute_order, check=False) else: @@ -1593,7 +1593,7 @@ def __and__(left, right): return left._absolute_order & right elif isinstance(left, RelativeOrder) and isinstance(right, RelativeOrder): if left._K != right._K: - raise TypeError, "Number fields don't match." + raise TypeError("Number fields don't match.") return RelativeOrder(left._K, left._absolute_order & right._absolute_order, check=False) else: @@ -1667,7 +1667,7 @@ def index_in(self, other): 8/729 """ if not isinstance(other, Order): - raise TypeError, "other must be an absolute order." + raise TypeError("other must be an absolute order.") return self.absolute_order().index_in(other.absolute_order()) @@ -1748,7 +1748,7 @@ def absolute_order_from_ring_generators(gens, check_is_integral=True, Order in Number Field in a with defining polynomial x^4 - 5 """ if check_is_integral and not each_is_integral(gens): - raise ValueError, "each generator must be integral" + raise ValueError("each generator must be integral") gens = Sequence(gens) K = gens.universe() n = [x.absolute_minpoly().degree() for x in gens] @@ -1851,10 +1851,10 @@ def absolute_order_from_module_generators(gens, Order in Number Field in alpha with defining polynomial x^4 + 3 """ if len(gens) == 0: - raise ValueError, "gens must span an order over ZZ" + raise ValueError("gens must span an order over ZZ") gens = Sequence(gens) if check_integral and not each_is_integral(gens): - raise ValueError, "each generator must be integral" + raise ValueError("each generator must be integral") K = gens.universe() if is_NumberFieldOrder(K): @@ -1884,13 +1884,13 @@ def absolute_order_from_module_generators(gens, elif check_rank: if W.rank() != K.degree(): - raise ValueError, "the rank of the span of gens is wrong" + raise ValueError("the rank of the span of gens is wrong") if check_is_ring: # Is there a faster way? alg = [to_V(x) for x in monomials(gens, [f.absolute_minpoly().degree() for f in gens])] if ambient.span(alg) != W: - raise ValueError, "the module span of the gens is not closed under multiplication." + raise ValueError("the module span of the gens is not closed under multiplication.") return AbsoluteOrder(K, W, check=False, is_maximal=is_maximal) # we have already checked everything @@ -1931,7 +1931,7 @@ def relative_order_from_ring_generators(gens, [1, 7*i - 2*a, -a*i + 8, 25*i - 7*a] """ if check_is_integral and not each_is_integral(gens): - raise ValueError, "each generator must be integral" + raise ValueError("each generator must be integral") gens = Sequence(gens) # The top number field that contains the order. diff --git a/src/sage/rings/number_field/totallyreal_phc.py b/src/sage/rings/number_field/totallyreal_phc.py index 82c5d5c30e5..dd62402a3d5 100644 --- a/src/sage/rings/number_field/totallyreal_phc.py +++ b/src/sage/rings/number_field/totallyreal_phc.py @@ -105,7 +105,7 @@ def __lagrange_bounds_phc(n, m, a, tmpfile=None): fi.close() fo.close() if find_phc == []: - raise RuntimeError, "PHCpack not installed." + raise RuntimeError("PHCpack not installed.") # Initialization. if tmpfile is None: diff --git a/src/sage/rings/number_field/totallyreal_rel.py b/src/sage/rings/number_field/totallyreal_rel.py index da090b1bc0e..75e3399fe67 100644 --- a/src/sage/rings/number_field/totallyreal_rel.py +++ b/src/sage/rings/number_field/totallyreal_rel.py @@ -313,9 +313,9 @@ def __init__(self, F, m, B, a=None): # currently unknown; e.g., if k == -1, then we can iterate # over polynomials, and if k == n-1, then we have finished iterating. if a[len(a)-1] != 1: - raise ValueError, "a[len(a)-1](=%s) must be 1 so polynomial is monic"%a[len(a)-1] + raise ValueError("a[len(a)-1](=%s) must be 1 so polynomial is monic"%a[len(a)-1]) - raise NotImplementedError, "These have not been checked." + raise NotImplementedError("These have not been checked.") k = m-len(a) self.k = k @@ -342,7 +342,7 @@ def __init__(self, F, m, B, a=None): self.gnk[k+1] = [[0] + [binomial(j,k+1)*v(a[j]) for j in range (k+2,m+1)] for v in self.Foo] else: # Bad input! - raise ValueError, "a has length %s > m+1"%len(a) + raise ValueError("a has length %s > m+1"%len(a)) def incr(self, f_out, verbose=False, haltk=0): r""" @@ -728,9 +728,9 @@ def enumerate_totallyreal_fields_rel(F, m, B, a = [], verbose=0, try: m = Integer(m) except TypeError: - raise TypeError, "cannot coerce m (= %s) to an integer" % m + raise TypeError("cannot coerce m (= %s) to an integer" % m) if (m < 1): - raise ValueError, "m must be at least 1." + raise ValueError("m must be at least 1.") n = F.degree()*m @@ -969,7 +969,7 @@ def enumerate_totallyreal_fields_all(n, B, verbose=0, return_seqs=False, S = [] counts = [0,0,0,0] if len(divisors(n)) > 4: - raise ValueError, "Only implemented for n = p*q with p,q prime" + raise ValueError("Only implemented for n = p*q with p,q prime") for d in divisors(n): if d > 1 and d < n: Sds = enumerate_totallyreal_fields_prim(d, int(math.floor((1.*B)**(1.*d/n))), verbose=verbose) diff --git a/src/sage/rings/number_field/unit_group.py b/src/sage/rings/number_field/unit_group.py index 7a135f5f14e..9dfed7cd9cd 100644 --- a/src/sage/rings/number_field/unit_group.py +++ b/src/sage/rings/number_field/unit_group.py @@ -346,14 +346,14 @@ def _element_constructor_(self, u): try: u = K(u) except TypeError: - raise ValueError, "%s is not an element of %s"%(u,K) + raise ValueError("%s is not an element of %s"%(u,K)) if self.__S: m = pK.bnfissunit(self.__S_unit_data, pari(u)).mattranspose() if m.ncols()==0: - raise ValueError, "%s is not an S-unit"%u + raise ValueError("%s is not an S-unit"%u) else: if not u.is_integral() or u.norm().abs() != 1: - raise ValueError, "%s is not a unit"%u + raise ValueError("%s is not a unit"%u) m = pK.bnfisunit(pari(u)).mattranspose() # convert column matrix to a list: @@ -508,7 +508,7 @@ def zeta(self, n=2, all=False): K = self.number_field() n = ZZ(n) if n <= 0: - raise ValueError, "n (=%s) must be positive"%n + raise ValueError("n (=%s) must be positive"%n) if n == 1: if all: return [K(1)] @@ -529,7 +529,7 @@ def zeta(self, n=2, all=False): if all: return [] else: - raise ValueError, "n (=%s) does not divide order of generator"%n + raise ValueError("n (=%s) does not divide order of generator"%n) def number_field(self): """ diff --git a/src/sage/rings/padics/eisenstein_extension_generic.py b/src/sage/rings/padics/eisenstein_extension_generic.py index 800be5881dc..b45a5fbfd0e 100644 --- a/src/sage/rings/padics/eisenstein_extension_generic.py +++ b/src/sage/rings/padics/eisenstein_extension_generic.py @@ -199,7 +199,7 @@ def gen(self, n=0): t + O(t^21) """ if n != 0: - raise IndexError, "only one generator" + raise IndexError("only one generator") return self([0,1]) def uniformizer_pow(self, n): diff --git a/src/sage/rings/padics/factory.py b/src/sage/rings/padics/factory.py index f464f4dac56..85408387dca 100644 --- a/src/sage/rings/padics/factory.py +++ b/src/sage/rings/padics/factory.py @@ -81,7 +81,7 @@ def get_key_base(p, prec, type, print_mode, halt, names, ram_name, print_pos, pr if not isinstance(halt, Integer): halt = Integer(halt) if not p.is_prime(): - raise ValueError, "p must be prime" + raise ValueError("p must be prime") print_ram_name = ram_name if isinstance(print_mode, dict): if 'pos' in print_mode: @@ -136,7 +136,7 @@ def get_key_base(p, prec, type, print_mode, halt, names, ram_name, print_pos, pr if not isinstance(print_ram_name, str): print_ram_name = str(print_ram_name) if names != print_ram_name: - raise ValueError, "If both names (%s) and print_ram_name (%s) are specified, they must agree"%(names, print_ram_name) + raise ValueError("If both names (%s) and print_ram_name (%s) are specified, they must agree"%(names, print_ram_name)) name = names else: if names is None: @@ -151,7 +151,7 @@ def get_key_base(p, prec, type, print_mode, halt, names, ram_name, print_pos, pr key = (p, prec, halt, print_mode, name, print_pos, print_sep, tuple(print_alphabet), print_max_terms) else: print type - raise ValueError, "type must be %s or lazy"%(", ".join(valid_non_lazy_types)) + raise ValueError("type must be %s or lazy"%(", ".join(valid_non_lazy_types))) return key ####################################################################################################### @@ -485,7 +485,7 @@ def create_object(self, version, key): p, prec, type, print_mode, name, print_pos, print_sep, print_alphabet, print_max_terms = key if isinstance(type, Integer): # lazy - raise NotImplementedError, "lazy p-adics need more work. Sorry." + raise NotImplementedError("lazy p-adics need more work. Sorry.") if version[0] < 4 or (len(version) > 1 and version[0] == 4 and version[1] < 5) or (len(version) > 2 and version[0] == 4 and version[1] == 5 and version[2] < 3): # keys changed in order to reduce irrelevant duplications: e.g. two Qps with print_mode 'series' that are identical except for different 'print_alphabet' now return the same object. key = get_key_base(p, prec, type, print_mode, 0, name, None, print_pos, print_sep, print_alphabet, print_max_terms, False, ['capped-rel', 'fixed-mod', 'capped-abs']) @@ -503,7 +503,7 @@ def create_object(self, version, key): else: return pAdicFieldCappedRelative(p, prec, {'mode': print_mode, 'pos': print_pos, 'sep': print_sep, 'alphabet': print_alphabet, 'ram_name': name, 'max_ram_terms': print_max_terms}, name) else: - raise ValueError, "unexpected type" + raise ValueError("unexpected type") Qp = Qp_class("Qp") @@ -948,21 +948,21 @@ def Qq(q, prec = DEFAULT_PREC, type = 'capped-rel', modulus = None, names=None, names = names[0] from sage.symbolic.expression import is_Expression if not (modulus is None or is_Polynomial(modulus) or is_Expression(modulus)): - raise TypeError, "modulus must be a polynomial" + raise TypeError("modulus must be a polynomial") if names is not None and not isinstance(names, str): names = str(names) #raise TypeError, "names must be a string" q = Integer(q) F = q.factor() if len(F) != 1: - raise ValueError, "q must be a prime power" + raise ValueError("q must be a prime power") else: F = q base = Qp(p=F[0][0], prec=prec, type=type, print_mode=print_mode, halt=halt, names=ram_name, print_pos=print_pos, print_sep=print_sep, print_max_terms=print_max_ram_terms, check=False) if F[0][1] == 1: return base elif names is None: - raise TypeError, "You must specify the name of the generator." + raise TypeError("You must specify the name of the generator.") if res_name is None: res_name = names + '0' if modulus is None: @@ -1436,7 +1436,7 @@ def create_object(self, version, key): p, prec, type, print_mode, name, print_pos, print_sep, print_alphabet, print_max_terms = key if isinstance(type, Integer): # lazy - raise NotImplementedError, "lazy p-adics need more work. Sorry." + raise NotImplementedError("lazy p-adics need more work. Sorry.") if version[0] < 4 or (len(version) > 1 and version[0] == 4 and version[1] < 5) or (len(version) > 2 and version[0] == 4 and version[1] == 5 and version[2] < 3): # keys changed in order to reduce irrelevant duplications: e.g. two Zps with print_mode 'series' that are identical except for different 'print_alphabet' now return the same object. key = get_key_base(p, prec, type, print_mode, 0, name, None, print_pos, print_sep, print_alphabet, print_max_terms, False, ['capped-rel', 'fixed-mod', 'capped-abs']) @@ -1454,7 +1454,7 @@ def create_object(self, version, key): elif type == 'capped-abs': return pAdicRingCappedAbsolute(p, prec, {'mode': print_mode, 'pos': print_pos, 'sep': print_sep, 'alphabet': print_alphabet, 'ram_name': name, 'max_ram_terms': print_max_terms}, name) else: - raise ValueError, "unexpected type" + raise ValueError("unexpected type") Zp = Zp_class("Zp") @@ -1923,21 +1923,21 @@ def Zq(q, prec = DEFAULT_PREC, type = 'capped-abs', modulus = None, names=None, names = names[0] from sage.symbolic.expression import is_Expression if not (modulus is None or is_Polynomial(modulus) or is_Expression(modulus)): - raise TypeError, "modulus must be a polynomial" + raise TypeError("modulus must be a polynomial") if names is not None and not isinstance(names, str): names = str(names) #raise TypeError, "names must be a string" q = Integer(q) F = q.factor() if len(F) != 1: - raise ValueError, "q must be a prime power" + raise ValueError("q must be a prime power") else: F = q base = Zp(p=F[0][0], prec=prec, type=type, print_mode=print_mode, halt=halt, names=ram_name, print_pos=print_pos, print_sep=print_sep, print_max_terms=print_max_ram_terms, check=False) if F[0][1] == 1: return base elif names is None: - raise TypeError, "You must specify the name of the generator." + raise TypeError("You must specify the name of the generator.") if res_name is None: res_name = names + '0' if modulus is None: @@ -2140,16 +2140,16 @@ def create_key_and_extra_args(self, base, premodulus, prec = None, print_mode = if check: if is_Expression(premodulus): if len(premodulus.variables()) != 1: - raise ValueError, "symbolic expression must be in only one variable" + raise ValueError("symbolic expression must be in only one variable") modulus = premodulus.polynomial(base) elif is_Polynomial(premodulus): if premodulus.parent().ngens() != 1: - raise ValueError, "must use univariate polynomial" + raise ValueError("must use univariate polynomial") modulus = premodulus.change_ring(base) else: - raise ValueError, "modulus must be a polynomial" + raise ValueError("modulus must be a polynomial") if modulus.degree() <= 1: - raise NotImplementedError, "degree of modulus must be at least 2" + raise NotImplementedError("degree of modulus must be at least 2") # need to add more checking here. if not unram: #this is not quite the condition we want for not checking these things; deal with fixed-mod sanely if not modulus.is_monic(): @@ -2162,12 +2162,12 @@ def create_key_and_extra_args(self, base, premodulus, prec = None, print_mode = base = base.fraction_field() #Now modulus is monic if not krasner_check(modulus, prec): - raise ValueError, "polynomial does not determine a unique extension. Please specify more precision or use parameter check=False." + raise ValueError("polynomial does not determine a unique extension. Please specify more precision or use parameter check=False.") if names is None: if var_name is not None: names = var_name else: - raise ValueError, "must specify name of generator of extension" + raise ValueError("must specify name of generator of extension") if isinstance(names, tuple): names = names[0] if not isinstance(names, str): @@ -2326,7 +2326,7 @@ def split(poly, prec): NotImplementedError: Extensions by general polynomials not yet supported. Please use an unramified or Eisenstein polynomial. """ - raise NotImplementedError, "Extensions by general polynomials not yet supported. Please use an unramified or Eisenstein polynomial." + raise NotImplementedError("Extensions by general polynomials not yet supported. Please use an unramified or Eisenstein polynomial.") def truncate_to_prec(poly, absprec): """ diff --git a/src/sage/rings/padics/generic_nodes.py b/src/sage/rings/padics/generic_nodes.py index e4ea770601c..382c8c8f44d 100644 --- a/src/sage/rings/padics/generic_nodes.py +++ b/src/sage/rings/padics/generic_nodes.py @@ -304,7 +304,7 @@ def random_element(self, algorithm='default'): else: return self(ZZ.random_element(self.prime_pow.pow_Integer_Integer(self.precision_cap()))) else: - raise NotImplementedError, "Don't know %s algorithm"%algorithm + raise NotImplementedError("Don't know %s algorithm"%algorithm) #def unit_group(self): # raise NotImplementedError @@ -339,7 +339,7 @@ def composite(self, subfield1, subfield2): #should be overridden for extension fields if (subfield1 is self) and (subfield2 is self): return self - raise ValueError, "Arguments must be subfields of self." + raise ValueError("Arguments must be subfields of self.") def subfields_of_degree(self, n): r""" @@ -385,7 +385,7 @@ def subfield(self, list): """ for x in list: if not self.__contains__(x): - raise TypeError, "Members of the list of generators must be elements of self." + raise TypeError("Members of the list of generators must be elements of self.") return self def construction(self): diff --git a/src/sage/rings/padics/local_generic.py b/src/sage/rings/padics/local_generic.py index b46b5d05264..5b54181dc6c 100644 --- a/src/sage/rings/padics/local_generic.py +++ b/src/sage/rings/padics/local_generic.py @@ -344,7 +344,7 @@ def ramification_index(self, K = None): if K is None or K is self: return Integer(1) else: - raise ValueError, "K should be a subring of self" + raise ValueError("K should be a subring of self") def e(self, K = None): r""" diff --git a/src/sage/rings/padics/padic_base_generic.py b/src/sage/rings/padics/padic_base_generic.py index b9b0bbc695b..8641a0fe0e8 100644 --- a/src/sage/rings/padics/padic_base_generic.py +++ b/src/sage/rings/padics/padic_base_generic.py @@ -137,7 +137,7 @@ def gen(self, n=0): 5 + O(5^21) """ if n != 0: - raise IndexError, "only one generator" + raise IndexError("only one generator") return self(self.prime()) def absolute_discriminant(self): @@ -174,7 +174,7 @@ def discriminant(self, K=None): if (K is None or K is self): return 1 else: - raise ValueError, "Ground Ring must be a subring of self" + raise ValueError("Ground Ring must be a subring of self") def is_abelian(self): """ @@ -308,7 +308,7 @@ def zeta(self, n=None): if n == 1: return self(1) else: - raise ValueError, "No, %sth root of unity in self"%n + raise ValueError("No, %sth root of unity in self"%n) else: from sage.rings.finite_rings.constructor import GF return self.teichmuller(GF(self.prime()).zeta(n).lift()) diff --git a/src/sage/rings/padics/padic_base_leaves.py b/src/sage/rings/padics/padic_base_leaves.py index 87a4744160b..a43eb7ef9af 100644 --- a/src/sage/rings/padics/padic_base_leaves.py +++ b/src/sage/rings/padics/padic_base_leaves.py @@ -487,7 +487,7 @@ def fraction_field(self, print_mode = None): sage: a = ZpFM(5)(4); b = ZpFM(5)(5) """ - raise TypeError, "This implementation of the p-adic ring does not support fields of fractions." + raise TypeError("This implementation of the p-adic ring does not support fields of fractions.") class pAdicFieldCappedRelative(pAdicFieldBaseGeneric, pAdicCappedRelativeFieldGeneric): @@ -611,4 +611,4 @@ def random_element(self, algorithm='default'): a = ZZ.random_element(self.prime()**self.precision_cap()) return self(self.prime()**k * a, absprec = k + self.precision_cap()) else: - raise NotImplementedError, "Don't know %s algorithm"%algorithm + raise NotImplementedError("Don't know %s algorithm"%algorithm) diff --git a/src/sage/rings/padics/padic_generic.py b/src/sage/rings/padics/padic_generic.py index fdb4cf8b5b7..1fba8833650 100644 --- a/src/sage/rings/padics/padic_generic.py +++ b/src/sage/rings/padics/padic_generic.py @@ -848,7 +848,7 @@ def local_print_mode(obj, print_options, pos = None, ram_name = None): if isinstance(print_options, str): print_options = {'mode': print_options} elif not isinstance(print_options, dict): - raise TypeError, "print_options must be a dictionary or a string" + raise TypeError("print_options must be a dictionary or a string") if pos is not None: print_options['pos'] = pos if ram_name is not None: diff --git a/src/sage/rings/padics/unramified_extension_generic.py b/src/sage/rings/padics/unramified_extension_generic.py index 34e052e0969..26f28ce7629 100644 --- a/src/sage/rings/padics/unramified_extension_generic.py +++ b/src/sage/rings/padics/unramified_extension_generic.py @@ -209,7 +209,7 @@ def gen(self, n=0): a + O(5^20) """ if n != 0: - raise IndexError, "only one generator" + raise IndexError("only one generator") return self([0,1]) def uniformizer_pow(self, n): diff --git a/src/sage/rings/pari_ring.py b/src/sage/rings/pari_ring.py index 20bee475700..27749f780a3 100644 --- a/src/sage/rings/pari_ring.py +++ b/src/sage/rings/pari_ring.py @@ -180,7 +180,7 @@ def is_field(self, proof = True): return False def characteristic(self): - raise RuntimeError, "Not defined." + raise RuntimeError("Not defined.") #return 0 def random_element(self, x=None, y=None, distribution=None): diff --git a/src/sage/rings/polynomial/convolution.py b/src/sage/rings/polynomial/convolution.py index 9cf9bfdfb89..38d771d18e6 100644 --- a/src/sage/rings/polynomial/convolution.py +++ b/src/sage/rings/polynomial/convolution.py @@ -80,7 +80,7 @@ def convolution(L1, L2): True """ if (not len(L1)) or (not len(L2)): - raise ValueError, "cannot compute convolution of empty lists" + raise ValueError("cannot compute convolution of empty lists") if len(L1) <= 100 and len(L2) <= 100: # very arbitrary cutoff return _convolution_naive(L1, L2) diff --git a/src/sage/rings/polynomial/groebner_fan.py b/src/sage/rings/polynomial/groebner_fan.py index 3d81fa7898c..7d96f53af62 100644 --- a/src/sage/rings/polynomial/groebner_fan.py +++ b/src/sage/rings/polynomial/groebner_fan.py @@ -807,20 +807,20 @@ class to compute the Stanley-Reisner ideal of the tropical prevariety:: print "WARNING! Symmetry option not yet implemented!!" self.__verbose = verbose if not is_MPolynomialIdeal(I): - raise TypeError, "I must be a multivariate polynomial ideal" + raise TypeError("I must be a multivariate polynomial ideal") if prefix_check([str(R_gen) for R_gen in I.ring().gens()]) != True: - raise RuntimeError, "Ring variables cannot contain each other as prefixes" + raise RuntimeError("Ring variables cannot contain each other as prefixes") S = I.ring() R = S.base_ring() # todo: add support for ZZ, which only works for bases computation, not tropical intersections if not R.is_field(): - raise NotImplementedError, "Groebner fan computation only implemented over fields" + raise NotImplementedError("Groebner fan computation only implemented over fields") if not (R is QQ or (R.is_finite() and R.is_prime_field() and R.order() <= 32749)): # sage: previous_prime (2^15) # 32749 - raise NotImplementedError, "Groebner fan computation only implemented over Q or GF(p) for p <= 32749." + raise NotImplementedError("Groebner fan computation only implemented over Q or GF(p) for p <= 32749.") if S.ngens() > 52: - raise NotImplementedError, "Groebner fan computation only implemented for rings in at most 52 variables." + raise NotImplementedError("Groebner fan computation only implemented for rings in at most 52 variables.") self.__ideal = I self.__ring = S @@ -1106,7 +1106,7 @@ def gfan(self, cmd='bases', I=None, format=True): cmd += self._gfan_mod() s = gfan(I, cmd, verbose=self.__verbose, format=format) if s.strip() == '{': - raise RuntimeError, "Error running gfan command %s on %s"%(cmd, self) + raise RuntimeError("Error running gfan command %s on %s"%(cmd, self)) return s def __iter__(self): @@ -1414,7 +1414,7 @@ def _4d_to_3d(self, polyhedral_data): print 'fpoints: ' + str(fpoints) print adjacent_vertex print polyhedral_data.ieqs() - raise RuntimeError, adj + raise RuntimeError(adj) return edges def render3d(self, verbose = False): @@ -1605,7 +1605,7 @@ def tropical_basis(self, check=True, verbose = False): cmd += ' -h' if check: if I.dimension() != 1 + self.dimension_of_homogeneity_space(): - raise ValueError, "The ideal does not define a tropical curve." + raise ValueError("The ideal does not define a tropical curve.") B = self.gfan(cmd) if B.find(']') != -1: @@ -1726,7 +1726,7 @@ def mixed_volume(self): 15 """ if len(self.ring().variable_names()) != self.ideal().ngens(): - raise UserWarning, 'not a square system' + raise UserWarning('not a square system') return Integer(self.gfan(cmd='mixedvolume')) class ReducedGroebnerBasis(SageObject, list): diff --git a/src/sage/rings/polynomial/ideal.py b/src/sage/rings/polynomial/ideal.py index 81c9ba86daf..7dc5bc5718b 100644 --- a/src/sage/rings/polynomial/ideal.py +++ b/src/sage/rings/polynomial/ideal.py @@ -58,9 +58,9 @@ def residue_field(self, names=None, check=True): """ if check: if not self.ring().base_ring().is_finite(): - raise TypeError, "residue fields only supported for polynomial rings over finite fields." + raise TypeError("residue fields only supported for polynomial rings over finite fields.") if not self.is_prime(): - raise ValueError, "%s is not a prime ideal"%self + raise ValueError("%s is not a prime ideal"%self) from sage.rings.residue_field import ResidueField return ResidueField(self, names, check=False) diff --git a/src/sage/rings/polynomial/infinite_polynomial_element.py b/src/sage/rings/polynomial/infinite_polynomial_element.py index 31dd3d64007..d35bd5865ad 100644 --- a/src/sage/rings/polynomial/infinite_polynomial_element.py +++ b/src/sage/rings/polynomial/infinite_polynomial_element.py @@ -407,7 +407,7 @@ def __getattr__(self, s): try: return getattr(self._p,s) except AttributeError: - raise AttributeError, '%s has no attribute %s'%(self.__class__, s) + raise AttributeError('%s has no attribute %s'%(self.__class__, s)) def ring(self): """ @@ -1147,7 +1147,7 @@ def coefficient(self, monomial): else: return self else: - raise TypeError, "Objects of type %s have no coefficients in InfinitePolynomials"%(type(monomial)) + raise TypeError("Objects of type %s have no coefficients in InfinitePolynomials"%(type(monomial))) return self.parent()(res) ## Essentials for Buchberger diff --git a/src/sage/rings/polynomial/infinite_polynomial_ring.py b/src/sage/rings/polynomial/infinite_polynomial_ring.py index 1bfee2f8587..3c3e3e9f01a 100644 --- a/src/sage/rings/polynomial/infinite_polynomial_ring.py +++ b/src/sage/rings/polynomial/infinite_polynomial_ring.py @@ -308,9 +308,9 @@ def create_key(self, R, names=('x',), order='lex', implementation='dense'): if isinstance(names, list): names = tuple(names) if not names: - raise ValueError, "Infinite Polynomial Rings must have at least one generator" + raise ValueError("Infinite Polynomial Rings must have at least one generator") if len(names)>len(set(names)): - raise ValueError, "The variable names must be distinct" + raise ValueError("The variable names must be distinct") F = InfinitePolynomialFunctor(names,order,implementation) while hasattr(R,'construction'): C = R.construction() @@ -345,7 +345,7 @@ def create_object(self, version, key): else: F = C if not isinstance(F, InfinitePolynomialFunctor): - raise TypeError, "We expected an InfinitePolynomialFunctor, not %s"%type(F) + raise TypeError("We expected an InfinitePolynomialFunctor, not %s"%type(F)) if F._imple=='sparse': return InfinitePolynomialRing_sparse(R, F._gens, order=F._order) return InfinitePolynomialRing_dense(R, F._gens, order=F._order) @@ -444,14 +444,14 @@ def __getitem__(self, k): """ if not isinstance(k,basestring): - raise KeyError, "String expected" + raise KeyError("String expected") L = k.split('_') try: if len(L)==2: return self._D[L[0]][int(L[1])] except Exception: pass - raise KeyError, "%s is not a variable name"%k + raise KeyError("%s is not a variable name"%k) class GenDictWithBasering: """ @@ -540,7 +540,7 @@ def next(self): """ if len(self._D)<=1: - raise ValueError, "No next term for %s available"%self + raise ValueError("No next term for %s available"%self) return GenDictWithBasering(self._P.base_ring(), self._D[1:]) def __repr__(self): @@ -572,7 +572,7 @@ def __getitem__(self, k): return D[k] except KeyError: pass - raise KeyError, "%s is not a variable name of %s or its iterated base rings"%(k,self._P) + raise KeyError("%s is not a variable name of %s or its iterated base rings"%(k,self._P)) ############################################################## ## The sparse implementation @@ -662,17 +662,17 @@ def __init__(self, R, names, order): names = ['x'] for n in names: if not (isinstance(n,basestring) and n.isalnum() and (not n[0].isdigit())): - raise ValueError, "generator names must be alpha-numeric strings not starting with a digit, but %s isn't"%n + raise ValueError("generator names must be alpha-numeric strings not starting with a digit, but %s isn't"%n) if len(names)!=len(set(names)): - raise ValueError, "generator names must be pairwise different" + raise ValueError("generator names must be pairwise different") self._names = list(names) if not isinstance(order, basestring): - raise TypeError, "The monomial order must be given as a string" + raise TypeError("The monomial order must be given as a string") try: if not (hasattr(R,'is_ring') and R.is_ring() and hasattr(R,'is_commutative') and R.is_commutative()): raise TypeError except Exception: - raise TypeError, "The given 'base ring' (= %s) must be a commutative ring"%(R) + raise TypeError("The given 'base ring' (= %s) must be a commutative ring"%(R)) # now, the input is accepted if hasattr(R,'_underlying_ring'): @@ -891,7 +891,7 @@ def _element_constructor_(self, x): try: return sage_eval(x, self.gens_dict()) except Exception: - raise ValueError, "Can't convert %s into an element of %s" % (x, self) + raise ValueError("Can't convert %s into an element of %s" % (x, self)) if hasattr(x, 'parent') and isinstance(x.parent(), InfinitePolynomialRing_sparse): # the easy case - parent == self - is already past @@ -925,7 +925,7 @@ def _element_constructor_(self, x): try: return sage_eval(repr(x), self.gens_dict()) except Exception: - raise ValueError, "Can't convert %s into an element of %s" % (x, self) + raise ValueError("Can't convert %s into an element of %s" % (x, self)) # direct conversion will only be used if the underlying polynomials are libsingular. from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomial_libsingular, MPolynomialRing_libsingular @@ -950,7 +950,7 @@ def _element_constructor_(self, x): # This tests admissibility on the fly: VarList.sort(cmp=self.varname_cmp,reverse=True) except ValueError: - raise ValueError, "Can't convert %s into an element of %s - variables aren't admissible"%(x,self) + raise ValueError("Can't convert %s into an element of %s - variables aren't admissible"%(x,self)) xmaxind = max([int(v.split('_')[1]) for v in VarList]) try: # Apparently, in libsingular, the polyomial conversion is not done by @@ -966,13 +966,13 @@ def _element_constructor_(self, x): # conversion to self._P will be done in InfinitePolynomial.__init__ return InfinitePolynomial(self, x) except (ValueError, TypeError, NameError): - raise ValueError, "Can't convert %s (from %s, but variables %s) into an element of %s - no conversion into underlying polynomial ring %s"%(x,x.parent(),x.variables(),self,self._P) + raise ValueError("Can't convert %s (from %s, but variables %s) into an element of %s - no conversion into underlying polynomial ring %s"%(x,x.parent(),x.variables(),self,self._P)) # By now, x or self._P are not libsingular. Since MPolynomialRing_polydict # is too buggy, we use string evaluation try: return sage_eval(repr(x),self._gens_dict) except (ValueError, TypeError, NameError): - raise ValueError, "Can't convert %s into an element of %s - no conversion into underlying polynomial ring"%(x,self) + raise ValueError("Can't convert %s into an element of %s - no conversion into underlying polynomial ring"%(x,self)) # By now, we are in the sparse case. try: @@ -983,7 +983,7 @@ def _element_constructor_(self, x): # This tests admissibility on the fly: VarList.sort(cmp=self.varname_cmp,reverse=True) except ValueError: - raise ValueError, "Can't convert %s into an element of %s - variables aren't admissible"%(x,self) + raise ValueError("Can't convert %s into an element of %s - variables aren't admissible"%(x,self)) if len(VarList)==1: # univariate polynomial rings are crab. So, make up another variable. @@ -1002,7 +1002,7 @@ def _element_constructor_(self, x): try: VarList.sort(cmp=self.varname_cmp,reverse=True) except ValueError: - raise ValueError, "Can't convert %s into an element of %s; the variables aren't admissible"%(x,self) + raise ValueError("Can't convert %s into an element of %s; the variables aren't admissible"%(x,self)) from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing R = PolynomialRing(self._base, VarList, order=self._order) @@ -1019,12 +1019,12 @@ def _element_constructor_(self, x): try: return sage_eval(repr(x), self._gens_dict) except (ValueError,TypeError,NameError): - raise ValueError, "Can't convert %s into an element of %s; conversion of the underlying polynomial failed"%(x,self) + raise ValueError("Can't convert %s into an element of %s; conversion of the underlying polynomial failed"%(x,self)) else: try: return sage_eval(repr(x), self._gens_dict) except (ValueError,TypeError,NameError): - raise ValueError, "Can't convert %s into an element of %s"%(x,self) + raise ValueError("Can't convert %s into an element of %s"%(x,self)) def tensor_with_ring(self, R): """ @@ -1060,7 +1060,7 @@ def tensor_with_ring(self, R): True """ if not R.has_coerce_map_from(self._underlying_ring): - raise TypeError, "We can't tensor with "+repr(R) + raise TypeError("We can't tensor with "+repr(R)) B = self.base_ring() if hasattr(B,'tensor_with_ring'): return InfinitePolynomialRing(B.tensor_with_ring(R), self._names, self._order, implementation='sparse') @@ -1070,7 +1070,7 @@ def tensor_with_ring(self, R): try: o = B.one_element()*R.one_element() except Exception: - raise TypeError, "We can't tensor with "+repr(R) + raise TypeError("We can't tensor with "+repr(R)) return InfinitePolynomialRing(o.parent(), self._names, self._order, implementation='sparse') ## Basic Ring Properties @@ -1166,7 +1166,7 @@ def varname_cmp(self,x,y): try: return cmp(self._identify_variable(*x.split('_',1)),self._identify_variable(*y.split('_',1))) except (KeyError, ValueError, TypeError): - raise ValueError, "%s or %s is not a valid variable name"%(x,y) + raise ValueError("%s or %s is not a valid variable name"%(x,y)) def ngens(self): """ @@ -1411,10 +1411,10 @@ def __getitem__(self, i): """ if int(i)!=i: - raise ValueError, "The index (= %s) must be an integer"%i + raise ValueError("The index (= %s) must be an integer"%i) i = int(i) if i < 0: - raise ValueError, "The index (= %s) must be non-negative"%i + raise ValueError("The index (= %s) must be non-negative"%i) P = self._parent from sage.rings.polynomial.infinite_polynomial_element import InfinitePolynomial_dense, InfinitePolynomial_sparse from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing @@ -1432,7 +1432,7 @@ def __getitem__(self, i): try: names = [ [name+'_'+str(j) for name in P._names] for j in range(i+1)] except OverflowError: - raise IndexError, "Variable index is too big - consider using the sparse implementation" + raise IndexError("Variable index is too big - consider using the sparse implementation") names = reduce(operator.add, names) names.sort(cmp=P.varname_cmp,reverse=True) #Create the new polynomial ring @@ -1560,7 +1560,7 @@ def tensor_with_ring(self, R): """ if not R.has_coerce_map_from(self._underlying_ring): - raise TypeError, "We can't tensor with "+repr(R) + raise TypeError("We can't tensor with "+repr(R)) B = self.base_ring() if hasattr(B,'tensor_with_ring'): return InfinitePolynomialRing(B.tensor_with_ring(R), self._names, self._order, implementation='dense') @@ -1570,7 +1570,7 @@ def tensor_with_ring(self, R): try: o = B.one_element()*R.one_element() except Exception: - raise TypeError, "We can't tensor with "+repr(R) + raise TypeError("We can't tensor with "+repr(R)) return InfinitePolynomialRing(o.parent(), self._names, self._order, implementation='dense') def polynomial_ring(self): diff --git a/src/sage/rings/polynomial/laurent_polynomial_ring.py b/src/sage/rings/polynomial/laurent_polynomial_ring.py index 73f36a924da..6b4ddf1e1ad 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_ring.py +++ b/src/sage/rings/polynomial/laurent_polynomial_ring.py @@ -233,10 +233,10 @@ def LaurentPolynomialRing(base_ring, arg1=None, arg2=None, sparse = False, order arg1 = name if not is_Ring(base_ring): - raise TypeError, 'base_ring must be a ring' + raise TypeError('base_ring must be a ring') if arg1 is None: - raise TypeError, "You must specify the names of the variables." + raise TypeError("You must specify the names of the variables.") R = None if isinstance(arg1, (list, tuple)): @@ -246,7 +246,7 @@ def LaurentPolynomialRing(base_ring, arg1=None, arg2=None, sparse = False, order if isinstance(arg2, (int, long, Integer)): # 3. LaurentPolynomialRing(base_ring, names, n, order='degrevlex'): if not isinstance(arg1, (list, tuple, str)): - raise TypeError, "You *must* specify the names of the variables." + raise TypeError("You *must* specify the names of the variables.") n = int(arg2) names = arg1 R = _multi_variate(base_ring, names, n, sparse, order) @@ -257,13 +257,13 @@ def LaurentPolynomialRing(base_ring, arg1=None, arg2=None, sparse = False, order if not ',' in arg1: # 1. LaurentPolynomialRing(base_ring, name, sparse=False): if not arg2 is None: - raise TypeError, "if second arguments is a string with no commas, then there must be no other non-optional arguments" + raise TypeError("if second arguments is a string with no commas, then there must be no other non-optional arguments") name = arg1 R = _single_variate(base_ring, name, sparse) else: # 2-4. LaurentPolynomialRing(base_ring, names, order='degrevlex'): if not arg2 is None: - raise TypeError, "invalid input to LaurentPolynomialRing function; please see the docstring for that function" + raise TypeError("invalid input to LaurentPolynomialRing function; please see the docstring for that function") names = arg1.split(',') n = len(names) R = _multi_variate(base_ring, names, n, sparse, order) @@ -274,9 +274,9 @@ def LaurentPolynomialRing(base_ring, arg1=None, arg2=None, sparse = False, order R = _multi_variate(base_ring, names, n, sparse, order) if arg1 is None and arg2 is None: - raise TypeError, "you *must* specify the indeterminates (as not None)." + raise TypeError("you *must* specify the indeterminates (as not None).") if R is None: - raise TypeError, "invalid input (%s, %s, %s) to PolynomialRing function; please see the docstring for that function"%(base_ring, arg1, arg2) + raise TypeError("invalid input (%s, %s, %s) to PolynomialRing function; please see the docstring for that function"%(base_ring, arg1, arg2)) return R @@ -296,7 +296,7 @@ def _get_from_cache(key): if key in _cache: return _cache[key] # put () here to re-enable weakrefs except TypeError as msg: - raise TypeError, 'key = %s\n%s'%(key,msg) + raise TypeError('key = %s\n%s'%(key,msg)) return None def _save_in_cache(key, R): @@ -316,7 +316,7 @@ def _save_in_cache(key, R): #weakref.ref(R) _cache[key] = R except TypeError as msg: - raise TypeError, 'key = %s\n%s'%(key,msg) + raise TypeError('key = %s\n%s'%(key,msg)) def _single_variate(base_ring, names, sparse): """ @@ -469,7 +469,7 @@ def gen(self, i=0): ValueError: generator not defined """ if i < 0 or i >= self._n: - raise ValueError, "generator not defined" + raise ValueError("generator not defined") return self(self._R.gen(i)) def is_integral_domain(self, proof = True): @@ -795,9 +795,9 @@ def __init__(self, R, prepend_string, names): True """ if R.ngens() <= 0: - raise ValueError, "n must be positive" + raise ValueError("n must be positive") if not R.base_ring().is_integral_domain(): - raise ValueError, "base ring must be an integral domain" + raise ValueError("base ring must be an integral domain") LaurentPolynomialRing_generic.__init__(self, R, prepend_string, names) def _element_constructor_(self, x): diff --git a/src/sage/rings/polynomial/multi_polynomial_element.py b/src/sage/rings/polynomial/multi_polynomial_element.py index 3a12b2ba606..f7780d09d9d 100644 --- a/src/sage/rings/polynomial/multi_polynomial_element.py +++ b/src/sage/rings/polynomial/multi_polynomial_element.py @@ -144,7 +144,7 @@ def __call__(self, *x, **kwds): x = x[0] n = self.parent().ngens() if len(x) != n: - raise TypeError, "x must be of correct length" + raise TypeError("x must be of correct length") if n == 0: return self try: @@ -295,7 +295,7 @@ def _div_(self, right): def __rpow__(self, n): if not isinstance(n, (int, long, sage.rings.integer.Integer)): - raise TypeError, "The exponent must be an integer." + raise TypeError("The exponent must be an integer.") return self.parent()(self.__element**n) def element(self): @@ -501,7 +501,7 @@ def degree(self, x=None): if x is None: return self.element().degree(None) if not (isinstance(x, MPolynomial) and x.parent() is self.parent() and x.is_generator()): - raise TypeError, "x must be one of the generators of the parent." + raise TypeError("x must be one of the generators of the parent.") return self.element().degree(x.element()) def total_degree(self): @@ -597,7 +597,7 @@ def monomial_coefficient(self, mon): -a """ if not (isinstance(mon, MPolynomial) and mon.parent() is self.parent() and mon.is_monomial()): - raise TypeError, "mon must be a monomial in the parent of self." + raise TypeError("mon must be a monomial in the parent of self.") R = self.parent().base_ring() return R(self.element().monomial_coefficient(mon.element().dict())) @@ -757,7 +757,7 @@ def coefficient(self, degrees): if d == poly_vars[i]: looking_for[i] = exp if not looking_for: - raise ValueError, "You must pass a dictionary list or monomial." + raise ValueError("You must pass a dictionary list or monomial.") return self.parent()(self.element().polynomial_coefficient(looking_for)) def exponents(self): @@ -812,10 +812,10 @@ def inverse_of_unit(self): d = self.element().dict() k = d.keys() if len(k) != 1: - raise ArithmeticError, "is not a unit" + raise ArithmeticError("is not a unit") k = k[0] if k != polydict.ETuple([0]*self.parent().ngens()): - raise ArithmeticError, "is not a unit" + raise ArithmeticError("is not a unit") return ~d[k] def is_homogeneous(self): @@ -1129,7 +1129,7 @@ def univariate_polynomial(self, R=None): return R(self) if not self.is_univariate(): - raise TypeError, "polynomial must involve at most one variable" + raise TypeError("polynomial must involve at most one variable") #construct ring if None if R is None: @@ -1608,7 +1608,7 @@ def factor(self, proof=True): # raise error if trying to factor zero if self == 0: - raise ArithmeticError, "Prime factorization of 0 not defined." + raise ArithmeticError("Prime factorization of 0 not defined.") # if number of variables is zero ... if R.ngens() == 0: @@ -1629,9 +1629,9 @@ def factor(self, proof=True): base_ring = self.base_ring() if base_ring.is_finite(): if base_ring.characteristic() > 1<<29: - raise NotImplementedError, "Factorization of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented." + raise NotImplementedError("Factorization of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") if proof: - raise NotImplementedError, "proof = True factorization not implemented. Call factor with proof=False." + raise NotImplementedError("proof = True factorization not implemented. Call factor with proof=False.") R._singular_().set_ring() S = self._singular_().factorize() @@ -1674,7 +1674,7 @@ def lift(self,I): try: M = Is.lift(fs)._sage_(P) except TypeError: - raise ArithmeticError, "f is not in I" + raise ArithmeticError("f is not in I") return Sequence(M.list(), P, check=False, immutable=True) #def gcd(self, f): @@ -1789,7 +1789,7 @@ def reduce(self, I): I = I.gens() if not k.is_field(): - raise TypeError, "Can only reduce polynomials over fields." + raise TypeError("Can only reduce polynomials over fields.") try: fs = self._singular_() diff --git a/src/sage/rings/polynomial/multi_polynomial_ideal.py b/src/sage/rings/polynomial/multi_polynomial_ideal.py index 7557bf8886a..066a6fc398a 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ideal.py +++ b/src/sage/rings/polynomial/multi_polynomial_ideal.py @@ -951,9 +951,9 @@ def plot(self, singular=singular_default): - David Joyner (2006-02-12) """ if self.ring().characteristic() != 0: - raise TypeError, "base ring must have characteristic 0" + raise TypeError("base ring must have characteristic 0") if not self.is_principal(): - raise TypeError, "self must be principal" + raise TypeError("self must be principal") singular.lib('surf') I = singular(self) I.plot() @@ -1351,7 +1351,7 @@ def triangular_decomposition(self, algorithm=None, singular=singular_default): I = MPolynomialIdeal(Q, I.groebner_basis()[::-1]) if I.dimension() != 0: - raise TypeError, "dimension must be zero" + raise TypeError("dimension must be zero") from sage.libs.singular.function import singular_function from sage.libs.singular.function import lib as singular_lib @@ -1365,7 +1365,7 @@ def triangular_decomposition(self, algorithm=None, singular=singular_default): f = singular_function(algorithm[9:]) Tbar = f(I, attributes={I:{'isSB':1}}) else: - raise TypeError, "algorithm '%s' unknown"%algorithm + raise TypeError("algorithm '%s' unknown"%algorithm) T = Sequence([ MPolynomialIdeal(Q,t) for t in Tbar]) @@ -1435,7 +1435,7 @@ def dimension(self, singular=singular_default): self.__dimension = Integer(v.dim()) except TypeError: if not self.base_ring().is_field(): - raise NotImplementedError, "dimension() is implemented only over fields." + raise NotImplementedError("dimension() is implemented only over fields.") if self.ring().term_order().is_global(): verbose("Warning: falling back to very slow toy implementation.", level=0) # See Chapter 9, Section 1 of Cox, Little, O'Shea's "Ideals, Varieties, @@ -1474,7 +1474,7 @@ def dimension(self, singular=singular_default): min_dimension = len(J) return n - min_dimension else: - raise TypeError, "Local/unknown orderings not supported by 'toy_buchberger' implementation." + raise TypeError("Local/unknown orderings not supported by 'toy_buchberger' implementation.") return self.__dimension @require_field @@ -1722,7 +1722,7 @@ def _groebner_basis_singular_raw(self, algorithm="groebner", singular=singular_d elif algorithm=="stdfglm": S = obj.stdfglm() else: - raise TypeError, "algorithm '%s' unknown"%algorithm + raise TypeError("algorithm '%s' unknown"%algorithm) self.__gb_singular = S if prot == "sage": print @@ -1832,7 +1832,7 @@ def intersection(self, *others): for other in others: if not isinstance(other, MPolynomialIdeal_singular_repr) or other.ring() != R: - raise TypeError, "Intersection is only available for ideals of the same ring." + raise TypeError("Intersection is only available for ideals of the same ring.") import sage.libs.singular intersect = sage.libs.singular.ff.intersect @@ -2275,7 +2275,7 @@ def transformed_basis(self, algorithm="gwalk", other_ring=None, singular=singula return PolynomialSequence(nR, sorted([nR(f) for f in nIs],reverse=True), immutable=True) else: - raise TypeError, "Cannot convert basis with given algorithm" + raise TypeError("Cannot convert basis with given algorithm") @libsingular_standard_options def elimination_ideal(self, variables): @@ -2344,10 +2344,10 @@ def quotient(self, J): R = self.ring() if not isinstance(J, MPolynomialIdeal): - raise TypeError, "J needs to be a multivariate polynomial ideal" + raise TypeError("J needs to be a multivariate polynomial ideal") if not R is J.ring() and not R == J.ring(): - raise TypeError, "base rings do not match" + raise TypeError("base rings do not match") import sage.libs.singular quotient = sage.libs.singular.ff.quotient @@ -2623,7 +2623,7 @@ def _variety(T, V, v=None): d = self.dimension() if d > 0: - raise ValueError, "The dimension of the ideal is %s, but it should be 0"%d + raise ValueError("The dimension of the ideal is %s, but it should be 0"%d) if d == -1: return [] @@ -2640,7 +2640,7 @@ def _variety(T, V, v=None): verbose("Warning: falling back to very slow toy implementation.", level=0) T = toy_variety.triangular_factorization(self.groebner_basis()) else: - raise TypeError, "Local/unknown orderings not supported by 'toy_buchberger' implementation." + raise TypeError("Local/unknown orderings not supported by 'toy_buchberger' implementation.") V = [] for t in T: @@ -2908,7 +2908,7 @@ def __init__(self, ring, gens, coerce=True, side = "left"): """ if side == "right": - raise ValueError, "Only left and two-sided ideals are allowed." + raise ValueError("Only left and two-sided ideals are allowed.") Ideal_nc.__init__(self, ring, gens, coerce=coerce, side=side) def __call_singular(self, cmd, arg = None): @@ -3845,7 +3845,7 @@ def groebner_basis(self, algorithm='', deg_bound=None, mult_bound=None, prot=Fal verbose("Warning: falling back to very slow toy implementation.", level=0) gb = toy_buchberger.buchberger_improved(self, *args, **kwds) else: - raise TypeError, "Local/unknown orderings not supported by 'toy_buchberger' implementation." + raise TypeError("Local/unknown orderings not supported by 'toy_buchberger' implementation.") elif algorithm.startswith('singular:'): gb = self._groebner_basis_singular(algorithm[9:], deg_bound=deg_bound, mult_bound=mult_bound, prot=prot, *args, **kwds) @@ -4320,10 +4320,10 @@ def plot(self, *args, **kwds): try: RR._coerce_(K(1)) except TypeError: - raise NotImplementedError, "Plotting of curves over %s not implemented yet"%K + raise NotImplementedError("Plotting of curves over %s not implemented yet"%K) if not self.is_principal(): - raise TypeError, "Ideal must be principal." + raise TypeError("Ideal must be principal.") f = self.gens()[0] @@ -4334,16 +4334,16 @@ def plot(self, *args, **kwds): V = [(variables[0], None, None), (variables[1], None, None)] if len(args) > 2: - raise TypeError, "Expected up to 2 optional parameters but got %d."%len(args) + raise TypeError("Expected up to 2 optional parameters but got %d."%len(args)) # first check whether user supplied boundaries for e in args: if not isinstance(e, (tuple, list)) or len(e) != 3: - raise TypeError, "Optional parameter must be list or tuple or length 3." + raise TypeError("Optional parameter must be list or tuple or length 3.") v,mi,ma = e if v not in variables: - raise TypeError, "Optional parameter must contain variable of ideal generator." + raise TypeError("Optional parameter must contain variable of ideal generator.") vi = variables.index(v) V[vi] = v,mi,ma @@ -4372,7 +4372,7 @@ def plot(self, *args, **kwds): elif len(variables) == 3 or kwds.get('algorithm','') == 'surf': MPolynomialIdeal_singular_repr.plot(self, kwds.get("singular",singular_default)) else: - raise TypeError, "Ideal generator may not have either 2 or 3 variables." + raise TypeError("Ideal generator may not have either 2 or 3 variables.") @require_field def weil_restriction(self): diff --git a/src/sage/rings/polynomial/multi_polynomial_ring.py b/src/sage/rings/polynomial/multi_polynomial_ring.py index 6fac6a78378..0c6e7146198 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring.py +++ b/src/sage/rings/polynomial/multi_polynomial_ring.py @@ -113,7 +113,7 @@ def _macaulay2_base_str(self): elif is_IntegerRing(self.base_ring()): return "ZZ" else: - raise TypeError, "no conversion of to a Macaulay2 ring defined" + raise TypeError("no conversion of to a Macaulay2 ring defined") def _macaulay2_set_ring(self, macaulay2): macaulay2.ring(self._macaulay2_base_str(), str(self.gens()), \ @@ -448,14 +448,14 @@ def __call__(self, x, check=True): if x.denominator() == 1: return x.numerator() else: - raise TypeError, "unable to coerce since the denominator is not 1" + raise TypeError("unable to coerce since the denominator is not 1") elif is_SingularElement(x) and self._has_singular: self._singular_().set_ring() try: return x.sage_poly(self) except TypeError: - raise TypeError, "unable to coerce singular object" + raise TypeError("unable to coerce singular object") elif hasattr(x, '_polynomial_'): return x._polynomial_(self) @@ -465,7 +465,7 @@ def __call__(self, x, check=True): from sage.misc.sage_eval import sage_eval return self(sage_eval(x, self.gens_dict_recursive())) except NameError as e: - raise TypeError, "unable to convert string" + raise TypeError("unable to convert string") elif is_Macaulay2Element(x): try: @@ -478,7 +478,7 @@ def __call__(self, x, check=True): # This took a while to figure out! return self(eval(s, {}, self.gens_dict())) except (AttributeError, TypeError, NameError, SyntaxError): - raise TypeError, "Unable to coerce macaulay2 object" + raise TypeError("Unable to coerce macaulay2 object") return MPolynomial_polydict(self, x) if isinstance(x, dict): @@ -859,7 +859,7 @@ def addwithcarry(tempvector, maxvector, pos): return tempvector if not t.is_monomial(): - raise TypeError, "Only monomials are supported" + raise TypeError("Only monomials are supported") R = self one = self.base_ring()(1) diff --git a/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py b/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py index 2a767544236..179625137c1 100644 --- a/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py +++ b/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py @@ -346,7 +346,7 @@ def content(self): 2 + O(2^11) """ if self.base_ring().is_field(): - raise TypeError, "ground ring is a field. Answer is only defined up to units." + raise TypeError("ground ring is a field. Answer is only defined up to units.") if self._normalized: return self.base_ring()(self.base_ring().prime_pow(self._valbase)) if self._valaddeds is None: @@ -677,9 +677,9 @@ def _unsafe_mutate(self, n, value): n = int(n) value = self.base_ring()(value) if self.is_gen(): - raise ValueError, "cannot modify generator" + raise ValueError("cannot modify generator") if n < 0: - raise IndexError, "n must be >= 0" + raise IndexError("n must be >= 0") if self._valbase is infinity: if value._is_exact_zero(): return @@ -913,7 +913,7 @@ def rescale(self, a): if msg == "element has negative valuation.": negval = True else: - raise ValueError, msg + raise ValueError(msg) if negval: return self.parent().base_extend(self.base_ring().fraction_field())(self).rescale(a) if self.base_ring().is_field() and a.valuation() < 0: @@ -943,7 +943,7 @@ def _quo_rem_naive(self, right): f = self.base_extend(K) g = right.base_extend(K) if g == 0: - raise ZeroDivisionError, "cannot divide by a polynomial indistinguishable from 0" + raise ZeroDivisionError("cannot divide by a polynomial indistinguishable from 0") x = f.parent().gen() quo = f.parent()(0) while f.degree() >= g.degree(): @@ -1128,11 +1128,11 @@ def factor_mod(self): """ self._normalize() if self._valbase < 0: - raise ValueError, "Polynomial does not have integral coefficients" + raise ValueError("Polynomial does not have integral coefficients") elif self._valbase > 0: - raise ValueError, "Factorization of the zero polynomial not defined" + raise ValueError("Factorization of the zero polynomial not defined") elif min(self._relprecs) <= 0: - raise PrecisionError, "Polynomial is not known to high enough precision" + raise PrecisionError("Polynomial is not known to high enough precision") return self._poly.factor_mod(self.base_ring().prime()) def _extend_by_infinity(L, n): @@ -1142,4 +1142,4 @@ def make_padic_poly(parent, x, version): if version == 0: return parent(x, construct = True) else: - raise ValueError, "unknown pickling version" + raise ValueError("unknown pickling version") diff --git a/src/sage/rings/polynomial/padics/polynomial_padic_flat.py b/src/sage/rings/polynomial/padics/polynomial_padic_flat.py index 99ce0e45184..5517a2f6016 100644 --- a/src/sage/rings/polynomial/padics/polynomial_padic_flat.py +++ b/src/sage/rings/polynomial/padics/polynomial_padic_flat.py @@ -26,7 +26,7 @@ def __init__(self, parent, x=None, check=True, is_gen=False, construct=False, ab R = parent.base_ring() if sage.rings.fraction_field_element.is_FractionFieldElement(x): if x.denominator() != 1: - raise TypeError, "denominator must be 1" + raise TypeError("denominator must be 1") else: x = x.numerator() if isinstance(x, Polynomial): diff --git a/src/sage/rings/polynomial/polynomial_element_generic.py b/src/sage/rings/polynomial/polynomial_element_generic.py index 6544b31beb0..307f23b3dae 100644 --- a/src/sage/rings/polynomial/polynomial_element_generic.py +++ b/src/sage/rings/polynomial/polynomial_element_generic.py @@ -357,7 +357,7 @@ def _unsafe_mutate(self, n, value): value = self.base_ring()(value) x = self.__coeffs if n < 0: - raise IndexError, "polynomial coefficient index must be nonnegative" + raise IndexError("polynomial coefficient index must be nonnegative") if value == 0: if n in x: del x[n] @@ -612,7 +612,7 @@ def quo_rem(self, other): """ P = self.parent() if other.is_zero(): - raise ZeroDivisionError, "other must be nonzero" + raise ZeroDivisionError("other must be nonzero") # This is algorithm 3.1.1 in Cohen GTM 138 A = self diff --git a/src/sage/rings/polynomial/polynomial_quotient_ring.py b/src/sage/rings/polynomial/polynomial_quotient_ring.py index 51bcfb76bb2..8d9975dbada 100644 --- a/src/sage/rings/polynomial/polynomial_quotient_ring.py +++ b/src/sage/rings/polynomial/polynomial_quotient_ring.py @@ -155,14 +155,14 @@ def PolynomialQuotientRing(ring, polynomial, names=None): Univariate Quotient Polynomial Ring in xbar over Rational Field with modulus x^2 - 1 """ if not isinstance(ring, PolynomialRing_commutative): - raise TypeError, "ring must be a polynomial ring" + raise TypeError("ring must be a polynomial ring") if not isinstance(polynomial, polynomial_element.Polynomial): - raise TypeError, "must be a polynomial" + raise TypeError("must be a polynomial") if not polynomial.parent() == ring: - raise TypeError, "polynomial must be in ring" + raise TypeError("polynomial must be in ring") c = polynomial.leading_coefficient() if not c.is_unit(): - raise TypeError, "polynomial must have unit leading coefficient" + raise TypeError("polynomial must have unit leading coefficient") if names is None: names = tuple([x + 'bar' for x in ring.variable_names()]) else: @@ -303,13 +303,13 @@ def __init__(self, ring, polynomial, name=None): """ if not isinstance(ring, PolynomialRing_commutative): - raise TypeError, "R must be a univariate polynomial ring." + raise TypeError("R must be a univariate polynomial ring.") if not isinstance(polynomial, polynomial_element.Polynomial): - raise TypeError, "f must be a Polynomial" + raise TypeError("f must be a Polynomial") if polynomial.parent() != ring: - raise TypeError, "f must have parent R" + raise TypeError("f must have parent R") self.__ring = ring self.__polynomial = polynomial @@ -441,7 +441,7 @@ def _element_constructor_(self, x): try: return self.element_class(self, self.__ring(x), check=False) except TypeError: - raise TypeError, "unable to convert %s into an element of %s"%(x,repr(self)) + raise TypeError("unable to convert %s into an element of %s"%(x,repr(self))) def _coerce_map_from_(self, R): """ @@ -771,7 +771,7 @@ class of the image of the generator of the polynomial ring. gamma """ if n != 0: - raise IndexError, "Only one generator." + raise IndexError("Only one generator.") try: return self.__gen except AttributeError: @@ -845,10 +845,10 @@ def number_field(self): 17*alpha + 1 """ if self.characteristic() != 0: - raise ArithmeticError, "Polynomial quotient ring is not isomorphic to a number field (it has positive characteristic)." + raise ArithmeticError("Polynomial quotient ring is not isomorphic to a number field (it has positive characteristic).") if not isinstance(self.base_ring(), sage.rings.rational_field.RationalField): - raise NotImplementedError, "Computation of number field only implemented for quotients of the polynomial ring over the rational field." + raise NotImplementedError("Computation of number field only implemented for quotients of the polynomial ring over the rational field.") return sage.rings.number_field.all.NumberField(self.modulus(), self.variable_name()) def order(self): diff --git a/src/sage/rings/polynomial/polynomial_quotient_ring_element.py b/src/sage/rings/polynomial/polynomial_quotient_ring_element.py index 511d00fe2a2..e7facff0795 100644 --- a/src/sage/rings/polynomial/polynomial_quotient_ring_element.py +++ b/src/sage/rings/polynomial/polynomial_quotient_ring_element.py @@ -121,13 +121,13 @@ def __init__(self, parent, polynomial, check=True): commutative_ring_element.CommutativeRingElement.__init__(self, parent) if check: if not isinstance(parent, PolynomialQuotientRing_generic): - raise TypeError, "parent must be a polynomial quotient ring" + raise TypeError("parent must be a polynomial quotient ring") if not isinstance(polynomial, Polynomial): - raise TypeError, "polynomial must be a polynomial" + raise TypeError("polynomial must be a polynomial") if not polynomial in parent.polynomial_ring(): - raise TypeError, "polynomial must be in the polynomial ring of the parent" + raise TypeError("polynomial must be in the polynomial ring of the parent") f = parent.modulus() if polynomial.degree() >= f.degree() and polynomial.degree() >= 0: @@ -377,8 +377,7 @@ def __invert__(self): NotImplementedError: The base ring (=Ring of integers modulo 16) is not a field """ if self._polynomial.is_zero(): - raise ZeroDivisionError, \ - "element %s of quotient polynomial ring not invertible"%self + raise ZeroDivisionError("element %s of quotient polynomial ring not invertible"%self) if self._polynomial.is_one(): return self parent = self.parent() @@ -387,8 +386,7 @@ def __invert__(self): raise NotImplementedError("The base ring (=%s) is not a field" % base) g, _, a = parent.modulus().xgcd(self._polynomial) if g.degree() != 0: - raise ZeroDivisionError, \ - "element %s of quotient polynomial ring not invertible"%self + raise ZeroDivisionError("element %s of quotient polynomial ring not invertible"%self) c = g[0] return self.__class__(self.parent(), (~c)*a, check=False) diff --git a/src/sage/rings/polynomial/polynomial_ring.py b/src/sage/rings/polynomial/polynomial_ring.py index 5d33d0e0ed9..8d8393fee4b 100644 --- a/src/sage/rings/polynomial/polynomial_ring.py +++ b/src/sage/rings/polynomial/polynomial_ring.py @@ -417,7 +417,7 @@ def _element_constructor_(self, x=None, check=True, is_gen = False, construct=Fa try: return x.sage_poly(self) except Exception: - raise TypeError, "Unable to coerce singular object" + raise TypeError("Unable to coerce singular object") elif isinstance(x , str): try: from sage.misc.parser import Parser, LookupNameMaker @@ -425,15 +425,15 @@ def _element_constructor_(self, x=None, check=True, is_gen = False, construct=Fa p = Parser(Integer, R, LookupNameMaker({self.variable_name(): self.gen()}, R)) return self(p.parse(x)) except NameError: - raise TypeError,"Unable to coerce string" + raise TypeError("Unable to coerce string") elif isinstance(x, FractionFieldElement): if x.denominator().is_unit(): x = x.numerator() * x.denominator().inverse_of_unit() else: - raise TypeError, "denominator must be a unit" + raise TypeError("denominator must be a unit") elif isinstance(x, pari_gen): if x.type() == 't_RFRAC': - raise TypeError, "denominator must be a unit" + raise TypeError("denominator must be a unit") if x.type() != 't_POL': x = x.Polrev() elif isinstance(x, FiniteRingElement): @@ -491,7 +491,7 @@ def completion(self, p, prec=20, extras=None): from sage.rings.power_series_ring import PowerSeriesRing return PowerSeriesRing(self.base_ring(), name=self._names[0], default_prec=prec) else: - raise TypeError, "Cannot complete %s with respect to %s" % (self, p) + raise TypeError("Cannot complete %s with respect to %s" % (self, p)) def _coerce_map_from_(self, P): """ @@ -800,7 +800,7 @@ def base_extend(self, R): if R.has_coerce_map_from(self.base_ring()): return PolynomialRing(R, names=self.variable_name(), sparse=self.is_sparse()) else: - raise TypeError, "no such base extension" + raise TypeError("no such base extension") def change_ring(self, R): """ @@ -943,7 +943,7 @@ def cyclotomic_polynomial(self, n): x - 1 """ if n <= 0: - raise ArithmeticError, "n=%s must be positive"%n + raise ArithmeticError("n=%s must be positive"%n) elif n == 1: return self.gen() - 1 else: @@ -970,7 +970,7 @@ def gen(self, n=0): True """ if n != 0: - raise IndexError, "generator n not defined" + raise IndexError("generator n not defined") return self.__generator def gens_dict(self): @@ -1141,9 +1141,9 @@ def random_element(self, degree=2, *args, **kwds): """ if isinstance(degree, (list, tuple)): if len(degree) != 2: - raise ValueError, "degree argument must be an integer or a tuple of 2 integers (min_degree, max_degree)" + raise ValueError("degree argument must be an integer or a tuple of 2 integers (min_degree, max_degree)") if degree[0] > degree[1]: - raise ValueError, "minimum degree must be less or equal than maximum degree" + raise ValueError("minimum degree must be less or equal than maximum degree") degree = randint(*degree) R = self.base_ring() return self([R.random_element(*args, **kwds) for _ in xrange(degree+1)]) @@ -1296,7 +1296,7 @@ def polynomials( self, of_degree = None, max_degree = None ): return self._polys_degree( of_degree ) if max_degree is not None and of_degree is None: return self._polys_max( max_degree ) - raise ValueError, "you should pass exactly one of of_degree and max_degree" + raise ValueError("you should pass exactly one of of_degree and max_degree") def monics( self, of_degree = None, max_degree = None ): """ @@ -1357,7 +1357,7 @@ def monics( self, of_degree = None, max_degree = None ): return self._monics_degree( of_degree ) if max_degree is not None and of_degree is None: return self._monics_max( max_degree ) - raise ValueError, "you should pass exactly one of of_degree and max_degree" + raise ValueError("you should pass exactly one of of_degree and max_degree") class PolynomialRing_commutative(PolynomialRing_general, commutative_algebra.CommutativeAlgebra): """ @@ -1365,7 +1365,7 @@ class PolynomialRing_commutative(PolynomialRing_general, commutative_algebra.Com """ def __init__(self, base_ring, name=None, sparse=False, element_class=None, category=None): if base_ring not in _CommutativeRings: - raise TypeError, "Base ring %s must be a commutative ring."%repr(base_ring) + raise TypeError("Base ring %s must be a commutative ring."%repr(base_ring)) # We trust that, if a category is given, that it is useful. if category is None: category = polynomial_default_category(base_ring,False) @@ -1448,7 +1448,7 @@ def __init__(self, base_ring, name="x", sparse=False, implementation=None, element_class = Polynomial_integer_dense_flint self._implementation_names = (None, 'FLINT') else: - raise ValueError, "Unknown implementation %s for ZZ[x]"%implementation + raise ValueError("Unknown implementation %s for ZZ[x]"%implementation) PolynomialRing_commutative.__init__(self, base_ring, name=name, sparse=sparse, element_class=element_class) @@ -1825,7 +1825,7 @@ def lagrange_polynomial(self, points, algorithm="divided_difference", previous_r # return P else: - raise ValueError, "algorithm must be one of 'divided_difference' or 'neville'" + raise ValueError("algorithm must be one of 'divided_difference' or 'neville'") def fraction_field(self): """ @@ -2089,7 +2089,7 @@ def __init__(self, base_ring, name=None, element_class=None, self._implementation_names = (None, 'FLINT') self._implementation_repr = '' elif implementation == 'FLINT': - raise ValueError, "FLINT does not support modulus %s"%(self.__modulus) + raise ValueError("FLINT does not support modulus %s"%(self.__modulus)) if not element_class: self._implementation_names = ('NTL',) self._implementation_repr = ' (using NTL)' @@ -2169,7 +2169,7 @@ def __init__(self, base_ring, name="x", implementation=None): self._implementation_repr = '' element_class = Polynomial_zmod_flint elif implementation == 'FLINT': - raise ValueError, "FLINT does not support modulus %s"%(__modulus) + raise ValueError("FLINT does not support modulus %s"%(__modulus)) if not element_class: from sage.rings.polynomial.polynomial_modn_dense_ntl import \ Polynomial_dense_mod_p @@ -2311,7 +2311,7 @@ def polygen(ring_or_element, name="x"): elif ring.is_Ring(ring_or_element): base_ring = ring_or_element else: - raise TypeError, "input must be a ring or ring element" + raise TypeError("input must be a ring or ring element") from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing t = PolynomialRing(base_ring, name) diff --git a/src/sage/rings/polynomial/polynomial_singular_interface.py b/src/sage/rings/polynomial/polynomial_singular_interface.py index 82b4b9011bf..326b843295c 100644 --- a/src/sage/rings/polynomial/polynomial_singular_interface.py +++ b/src/sage/rings/polynomial/polynomial_singular_interface.py @@ -228,7 +228,7 @@ def _singular_init_(self, singular=singular_default): // block 2 : ordering C """ if not can_convert_to_singular(self): - raise TypeError, "no conversion of this ring to a Singular ring defined" + raise TypeError("no conversion of this ring to a Singular ring defined") if self.ngens()==1: _vars = '(%s)'%self.gen() @@ -327,7 +327,7 @@ def _singular_init_(self, singular=singular_default): elif base_ring is ZZ: self.__singular = singular.ring("(integer)", _vars, order=order, check=False) else: - raise TypeError, "no conversion to a Singular ring defined" + raise TypeError("no conversion to a Singular ring defined") return self.__singular diff --git a/src/sage/rings/polynomial/symmetric_ideal.py b/src/sage/rings/polynomial/symmetric_ideal.py index 0a8cc373405..a74af3047f6 100644 --- a/src/sage/rings/polynomial/symmetric_ideal.py +++ b/src/sage/rings/polynomial/symmetric_ideal.py @@ -920,7 +920,7 @@ def groebner_basis(self, tailreduce=False, reduced=True, algorithm=None, report= algorithm='' PARENT = self.ring() if not (hasattr(PARENT.base_ring(),'is_field') and PARENT.base_ring().is_field()): - raise TypeError, "The base ring (= %s) must be a field"%PARENT.base_ring() + raise TypeError("The base ring (= %s) must be a field"%PARENT.base_ring()) OUT = self.symmetrisation(tailreduce=tailreduce,report=report,use_full_group=use_full_group) if not (report is None): print "Symmetrisation done" diff --git a/src/sage/rings/polynomial/term_order.py b/src/sage/rings/polynomial/term_order.py index 87d5de889ef..3154cf63132 100644 --- a/src/sage/rings/polynomial/term_order.py +++ b/src/sage/rings/polynomial/term_order.py @@ -652,7 +652,7 @@ def __init__(self, name='lex', n=0, force=False): name = name.list() # name may be a matrix name = tuple(name) except Exception: - raise TypeError, "%s is not a valid term order"%(name,) + raise TypeError("%s is not a valid term order"%(name,)) self._blocks = tuple() self._weights = None @@ -678,7 +678,7 @@ def __init__(self, name='lex', n=0, force=False): macaulay2_str.append("%s"%(t.macaulay2_str()[1:-1],)) else: if len(t) == 0: - raise ArithmeticError, "Can only concatenate term orders with length attribute." + raise ArithmeticError("Can only concatenate term orders with length attribute.") blocks.append(t) if t.is_weighted_degree_order(): # true if t is a matrix order as well singular_str.append("%s"%(t.singular_str(),)) @@ -708,7 +708,7 @@ def __init__(self, name='lex', n=0, force=False): block_names = re.findall(split_pattern,name) if len(block_names) == 0: - raise TypeError, "No term order specified" + raise TypeError("No term order specified") elif len(block_names) == 1: name = block_names[0] match = re.match('m\(([-+0-9,]+)\)$',name) @@ -717,7 +717,7 @@ def __init__(self, name='lex', n=0, force=False): self.__copy(TermOrder(m)) else: # simple order if name not in print_name_mapping.keys() and name not in singular_name_mapping.values(): - raise TypeError, "Unknown term order '%s'"%(name,) + raise TypeError("Unknown term order '%s'"%(name,)) self._length = n self._name = name self._singular_str = singular_name_mapping.get(name,name) @@ -745,17 +745,17 @@ def __init__(self, name='lex', n=0, force=False): except ValueError: block_name = block.strip() if block_name.lower() != "c": - raise TypeError, "%s is not a valid term ordering (wrong part: '%s')"%(name, block) + raise TypeError("%s is not a valid term ordering (wrong part: '%s')"%(name, block)) if n != 0 and length != n: - raise TypeError, "Term order length does not match the number of generators" + raise TypeError("Term order length does not match the number of generators") self.__copy(TermOrder('block', blocks)) elif isinstance(name, str) and (isinstance(n, tuple) or isinstance(n,list)): # weighted degree term orders if name not in print_name_mapping.keys() and name not in singular_name_mapping.values() and not force: - raise TypeError, "Unknown term order '%s'"%(name,) + raise TypeError("Unknown term order '%s'"%(name,)) weights = tuple(int(w) for w in n) # n is a tuple of weights if any([w<=0 for w in weights]): - raise ValueError, "the degree weights must be positive integers" + raise ValueError("the degree weights must be positive integers") self._length = len(weights) self._name = name @@ -768,7 +768,7 @@ def __init__(self, name='lex', n=0, force=False): from math import sqrt n = int(sqrt(len(name))) if n**2 != len(name): - raise TypeError, "%s does not specify a square matrix"%(name,) + raise TypeError("%s does not specify a square matrix"%(name,)) int_str = ','.join([str(int(e)) for e in name]) @@ -782,7 +782,7 @@ def __init__(self, name='lex', n=0, force=False): self._matrix = matrix(n,name) # defined only for matrix term order self._weights = name[:n] # the first row of the matrix gives weights else: - raise TypeError, "%s is not a valid term order"%(name,) + raise TypeError("%s is not a valid term order"%(name,)) if self._length != 0: self._singular_str = self._singular_str%dict(ngens=self._length) @@ -823,7 +823,7 @@ def __getattr__(self,name): elif name == 'greater_tuple': return getattr(self,'greater_tuple_'+self._name) else: - raise AttributeError,name + raise AttributeError(name) def compare_tuples_matrix(self,f,g): """ @@ -2096,7 +2096,7 @@ def termorder_from_singular(S): else: order.append(TermOrder(inv_singular_name_mapping[blocktype], ZZ(singular.eval("size(%s[2])"%block.name())))) if not order: - raise ValueError, "Invalid term order in Singular" + raise ValueError("Invalid term order in Singular") out = order.pop(0) while order: out = out + order.pop(0) diff --git a/src/sage/rings/polynomial/toy_variety.py b/src/sage/rings/polynomial/toy_variety.py index 355f366761e..0af462d1442 100644 --- a/src/sage/rings/polynomial/toy_variety.py +++ b/src/sage/rings/polynomial/toy_variety.py @@ -72,7 +72,7 @@ def is_triangular(B): try: G = B.gens() except Exception: - raise TypeError, "is_triangular wants as input an ideal, or a list of polynomials\n" + raise TypeError("is_triangular wants as input an ideal, or a list of polynomials\n") vars = G[0].parent().gens() n = len(G) # We expect the polynomials of G to be ordered G[i].lm() > G[i+1].lm(); @@ -264,7 +264,7 @@ def triangular_factorization(B, n=-1): try: G = B.gens() except Exception: - raise TypeError, "triangular_factorization wants as input an ideal, or a list of polynomials\n" + raise TypeError("triangular_factorization wants as input an ideal, or a list of polynomials\n") # easy cases if len(G)==0: return list() @@ -333,7 +333,7 @@ def elim_pol(B, n=-1): try: G = B.gens() except Exception: - raise TypeError, "elim_pol wants as input an ideal or a list of polynomials" + raise TypeError("elim_pol wants as input an ideal or a list of polynomials") # setup -- main algorithm x = G[0].parent().gens()[n] diff --git a/src/sage/rings/power_series_ring.py b/src/sage/rings/power_series_ring.py index 7e14184ddea..8564ab4a666 100644 --- a/src/sage/rings/power_series_ring.py +++ b/src/sage/rings/power_series_ring.py @@ -370,10 +370,10 @@ def PowerSeriesRing(base_ring, name=None, arg2=None, names=None, try: name = normalize_names(1, name) except TypeError: - raise TypeError, "illegal variable name" + raise TypeError("illegal variable name") if name is None: - raise TypeError, "You must specify the name of the indeterminate of the Power series ring." + raise TypeError("You must specify the name of the indeterminate of the Power series ring.") key = (base_ring, name, default_prec, sparse) if PowerSeriesRing_generic.__classcall__.is_in_cache(key): @@ -384,7 +384,7 @@ def PowerSeriesRing(base_ring, name=None, arg2=None, names=None, name = name[0] if not (name is None or isinstance(name, str)): - raise TypeError, "variable name must be a string or None" + raise TypeError("variable name must be a string or None") if base_ring in _Fields: R = PowerSeriesRing_over_field(base_ring, name, default_prec, sparse=sparse) @@ -393,7 +393,7 @@ def PowerSeriesRing(base_ring, name=None, arg2=None, names=None, elif base_ring in _CommutativeRings: R = PowerSeriesRing_generic(base_ring, name, default_prec, sparse=sparse) else: - raise TypeError, "base_ring must be a commutative ring" + raise TypeError("base_ring must be a commutative ring") return R def _multi_variate(base_ring, num_gens=None, names=None, @@ -420,7 +420,7 @@ def _multi_variate(base_ring, num_gens=None, names=None, default_prec = 12 if base_ring not in commutative_rings.CommutativeRings(): - raise TypeError, "base_ring must be a commutative ring" + raise TypeError("base_ring must be a commutative ring") from sage.rings.multi_power_series_ring import MPowerSeriesRing_generic R = MPowerSeriesRing_generic(base_ring, num_gens, names, order=order, default_prec=default_prec, sparse=sparse) @@ -771,7 +771,7 @@ def _coerce_impl(self, x): if self.has_coerce_map_from(P.base_ring()): return self(x) else: - raise TypeError, "no natural map between bases of power series rings" + raise TypeError("no natural map between bases of power series rings") except AttributeError: pass @@ -845,7 +845,7 @@ def base_extend(self, R): if R.has_coerce_map_from(self.base_ring()): return self.change_ring(R) else: - raise TypeError, "no base extension defined" + raise TypeError("no base extension defined") def change_ring(self, R): """ @@ -884,7 +884,7 @@ def gen(self, n=0): IndexError: generator n>0 not defined """ if n != 0: - raise IndexError, "generator n>0 not defined" + raise IndexError("generator n>0 not defined") return self.__generator def uniformizer(self): diff --git a/src/sage/rings/qqbar.py b/src/sage/rings/qqbar.py index 75fd2b0d6af..aaeb4f16f67 100644 --- a/src/sage/rings/qqbar.py +++ b/src/sage/rings/qqbar.py @@ -853,7 +853,7 @@ def gen(self, n=0): if n == 0: return self(1) else: - raise IndexError, "n must be 0" + raise IndexError("n must be 0") def ngens(self): r""" @@ -1727,7 +1727,7 @@ def find_zero_result(fn, l): if ambig: continue if result is None: - raise ValueError, 'find_zero_result could not find any zeroes' + raise ValueError('find_zero_result could not find any zeroes') return result def conjugate_expand(v): @@ -3750,7 +3750,7 @@ def interval_diameter(self, diam): 1.41421356237309504880168872420969807857? """ if diam <= 0: - raise ValueError, 'diameter must be positive in interval_diameter' + raise ValueError('diameter must be positive in interval_diameter') while self._value.diameter() > diam: self._more_precision() diff --git a/src/sage/rings/quotient_ring.py b/src/sage/rings/quotient_ring.py index 19b81a875b5..774de6b79a6 100644 --- a/src/sage/rings/quotient_ring.py +++ b/src/sage/rings/quotient_ring.py @@ -265,7 +265,7 @@ def QuotientRing(R, I, names=None): # raise TypeError, "R must be a commutative ring." from sage.all import Integers, ZZ if not R in Rings(): - raise TypeError, "R must be a ring." + raise TypeError("R must be a ring.") try: is_commutative = R.is_commutative() except (AttributeError, NotImplementedError): @@ -291,7 +291,7 @@ def QuotientRing(R, I, names=None): if I.side() != 'twosided': raise AttributeError except AttributeError: - raise TypeError, "A twosided ideal is required." + raise TypeError("A twosided ideal is required.") if isinstance(R, QuotientRing_nc): pi = R.cover() S = pi.domain() @@ -430,9 +430,9 @@ def __init__(self, R, I, names, category=None): """ if R not in _Rings: - raise TypeError, "The first argument must be a ring, but %s is not"%R + raise TypeError("The first argument must be a ring, but %s is not"%R) if I not in R.ideal_monoid(): - raise TypeError, "The second argument must be an ideal of the given ring, but %s is not"%I + raise TypeError("The second argument must be an ideal of the given ring, but %s is not"%I) self.__R = R self.__I = I #sage.structure.parent_gens.ParentWithGens.__init__(self, R.base_ring(), names) @@ -567,7 +567,7 @@ def is_commutative(self): pass from sage.all import Infinity if self.ngens() == Infinity: - raise NotImplementedError, "This quotient ring has an infinite number of generators." + raise NotImplementedError("This quotient ring has an infinite number of generators.") for i in xrange(self.ngens()): gi = self.gen(i) for j in xrange(i+1,self.ngens()): @@ -1236,7 +1236,7 @@ def __init__(self, R, I, names, category=None): True """ if not isinstance(R, sage.rings.commutative_ring.CommutativeRing): - raise TypeError, "This class is for quotients of commutative rings only.\n For non-commutative rings, use " + raise TypeError("This class is for quotients of commutative rings only.\n For non-commutative rings, use ") if not self._is_category_initialized(): category = check_default_category(_CommutativeRingsQuotients,category) QuotientRing_nc.__init__(self, R, I, names, category=category) diff --git a/src/sage/rings/rational_field.py b/src/sage/rings/rational_field.py index 349c0f1724c..dc514845e2e 100644 --- a/src/sage/rings/rational_field.py +++ b/src/sage/rings/rational_field.py @@ -283,7 +283,7 @@ def __len__(self): ... TypeError: len() of unsized object """ - raise TypeError, 'len() of unsized object' + raise TypeError('len() of unsized object') def construction(self): r""" @@ -576,7 +576,7 @@ def embeddings(self, K): ValueError: no embeddings of the rational field into K. """ if K.characteristic() != 0: - raise ValueError, "no embeddings of the rational field into K." + raise ValueError("no embeddings of the rational field into K.") return [self.hom(K)] def complex_embedding(self, prec=53): @@ -625,7 +625,7 @@ def gen(self, n=0): if n == 0: return self(1) else: - raise IndexError, "n must be 0" + raise IndexError("n must be 0") def degree(self): r""" @@ -911,7 +911,7 @@ def zeta(self, n=2): elif n == 2: return rational.Rational(-1) else: - raise ValueError, "no n-th root of unity in rational field" + raise ValueError("no n-th root of unity in rational field") ################################# ## Coercions to interfaces diff --git a/src/sage/sandpiles/sandpile.py b/src/sage/sandpiles/sandpile.py index d518a1bf88d..55dfa76f7b0 100644 --- a/src/sage/sandpiles/sandpile.py +++ b/src/sage/sandpiles/sandpile.py @@ -323,7 +323,7 @@ def __init__(self, g, sink): processed_g[v] = edges g = processed_g else: - raise SyntaxError, g + raise SyntaxError(g) # create digraph and initialize some variables DiGraph.__init__(self,g,weighted=True) @@ -414,7 +414,7 @@ def __getattr__(self, name): self._set_points() return self.__dict__[name] else: - raise AttributeError, name + raise AttributeError(name) def version(self): r""" @@ -1377,7 +1377,7 @@ def nonspecial_divisors(self, verbose=True): else: return [r.values() for r in result] else: - raise UserWarning, "The underlying graph must be undirected." + raise UserWarning("The underlying graph must be undirected.") def canonical_divisor(self): r""" @@ -1401,7 +1401,7 @@ def canonical_divisor(self): if self.is_undirected(): return SandpileDivisor(self,[self.out_degree(v)-2 for v in self.vertices()]) else: - raise UserWarning, "Only for undirected graphs." + raise UserWarning("Only for undirected graphs.") def _set_invariant_factors(self): r""" @@ -2233,7 +2233,7 @@ def __init__(self, S, c): config[v] = c.pop() dict.__init__(self,config) else: - raise SyntaxError, c + raise SyntaxError(c) self._sandpile = S self._vertices = S.nonsink_vertices() @@ -2338,7 +2338,7 @@ def __getattr__(self, name): self._set_is_superstable() return self.__dict__[name] else: - raise AttributeError, name + raise AttributeError(name) def _set_deg(self): r""" @@ -3453,7 +3453,7 @@ def __init__(self, S, D): div[S.vertices()[i]] = D[i] dict.__init__(self,div) else: - raise SyntaxError, D + raise SyntaxError(D) self._sandpile = S self._vertices = S.vertices() @@ -3560,7 +3560,7 @@ def __getattr__(self, name): self._set_life() return self.__dict__[name] else: - raise AttributeError, name + raise AttributeError(name) def _set_deg(self): r""" @@ -5338,7 +5338,7 @@ def wilmes_algorithm(M): L[k] = L[k] + v return L else: - raise UserWarning, 'matrix not of full rank' + raise UserWarning('matrix not of full rank') ######### Notes ################ """ diff --git a/src/sage/schemes/affine/affine_homset.py b/src/sage/schemes/affine/affine_homset.py index 9298de86332..3df7cdd08b2 100644 --- a/src/sage/schemes/affine/affine_homset.py +++ b/src/sage/schemes/affine/affine_homset.py @@ -154,11 +154,11 @@ def points(self, B=0): R = self.value_ring() if is_RationalField(R) or R == ZZ: if not B > 0: - raise TypeError, "A positive bound B (= %s) must be specified."%B + raise TypeError("A positive bound B (= %s) must be specified."%B) from sage.schemes.affine.affine_rational_point import enum_affine_rational_field return enum_affine_rational_field(self,B) elif is_FiniteField(R): from sage.schemes.affine.affine_rational_point import enum_affine_finite_field return enum_affine_finite_field(self) else: - raise TypeError, "Unable to enumerate points over %s."%R + raise TypeError("Unable to enumerate points over %s."%R) diff --git a/src/sage/schemes/elliptic_curves/cm.py b/src/sage/schemes/elliptic_curves/cm.py index 9a8415a1657..7bbdd3f28c4 100644 --- a/src/sage/schemes/elliptic_curves/cm.py +++ b/src/sage/schemes/elliptic_curves/cm.py @@ -93,9 +93,9 @@ def hilbert_class_polynomial(D, algorithm=None): D = Integer(D) if D >= 0: - raise ValueError, "D (=%s) must be negative"%D + raise ValueError("D (=%s) must be negative"%D) if not (D%4 in [0,1]): - raise ValueError, "D (=%s) must be a discriminant"%D + raise ValueError("D (=%s) must be a discriminant"%D) if algorithm == "magma": magma.eval("R := PolynomialRing(IntegerRing())") @@ -103,7 +103,7 @@ def hilbert_class_polynomial(D, algorithm=None): return IntegerRing()['x'](f) if algorithm != "sage": - raise ValueError, "%s is not a valid algorithm"%algorithm + raise ValueError("%s is not a valid algorithm"%algorithm) from sage.quadratic_forms.binary_qf import BinaryQF_reduced_representatives from sage.rings.all import RR, ZZ, ComplexField @@ -361,7 +361,7 @@ class number `h`, and the number of fundamental discriminants with return (Integer(B), Integer(c)) except KeyError: # nobody knows, since I guess Watkins's is state of the art. - raise NotImplementedError, "largest discriminant not known for class number %s"%h + raise NotImplementedError("largest discriminant not known for class number %s"%h) def discriminants_with_bounded_class_number(hmax, B=None, proof=None): """ @@ -527,7 +527,7 @@ def classno(d): # data. for h in T.keys(): if len([D for D,f in T[h] if f==1]) != fund_count[h]: - raise RuntimeError, "number of discriminants inconsistent with Watkins's table" + raise RuntimeError("number of discriminants inconsistent with Watkins's table") return T diff --git a/src/sage/schemes/elliptic_curves/constructor.py b/src/sage/schemes/elliptic_curves/constructor.py index 6aba291e078..0173ce975c2 100644 --- a/src/sage/schemes/elliptic_curves/constructor.py +++ b/src/sage/schemes/elliptic_curves/constructor.py @@ -296,13 +296,13 @@ def EllipticCurve(x=None, y=None, j=None, minimal_twist=True): try: j = x(j) except (ZeroDivisionError, ValueError, TypeError): - raise ValueError, "First parameter must be a ring containing %s"%j + raise ValueError("First parameter must be a ring containing %s"%j) else: - raise ValueError, "First parameter (if present) must be a ring when j is specified" + raise ValueError("First parameter (if present) must be a ring when j is specified") return EllipticCurve_from_j(j, minimal_twist) if x is None: - raise TypeError, "invalid input to EllipticCurve constructor" + raise TypeError("invalid input to EllipticCurve constructor") if is_SymbolicEquation(x): x = x.lhs() - x.rhs() @@ -336,14 +336,14 @@ def EllipticCurve(x=None, y=None, j=None, minimal_twist=True): return ell_rational_field.EllipticCurve_rational_field(x) if is_RingElement(x) and y is None: - raise TypeError, "invalid input to EllipticCurve constructor" + raise TypeError("invalid input to EllipticCurve constructor") if not isinstance(x, (list, tuple)): - raise TypeError, "invalid input to EllipticCurve constructor" + raise TypeError("invalid input to EllipticCurve constructor") x = Sequence(x) if not (len(x) in [2,5]): - raise ValueError, "sequence of coefficients must have length 2 or 5" + raise ValueError("sequence of coefficients must have length 2 or 5") R = x.universe() if isinstance(x[0], (rings.Rational, rings.Integer, int, long)): diff --git a/src/sage/schemes/elliptic_curves/ell_curve_isogeny.py b/src/sage/schemes/elliptic_curves/ell_curve_isogeny.py index 5cdbbdf8741..0f500b37d9c 100644 --- a/src/sage/schemes/elliptic_curves/ell_curve_isogeny.py +++ b/src/sage/schemes/elliptic_curves/ell_curve_isogeny.py @@ -132,7 +132,7 @@ def isogeny_determine_algorithm(E, kernel, codomain, degree, model): elif (kernel_is_list) and (kernel[0] in E): # note that if kernel[0] is on an extension of E this condition will be false algorithm = "velu" else: - raise ValueError, "Invalid Parameters to EllipticCurveIsogeny constructor." + raise ValueError("Invalid Parameters to EllipticCurveIsogeny constructor.") return algorithm @@ -356,7 +356,7 @@ def compute_codomain_kohel(E, kernel, degree): psi = poly_ring(kernel_list) x = poly_ring.gen() else: - raise ValueError, "input not of correct type" + raise ValueError("input not of correct type") # next determine the even / odd part of the isogeny @@ -367,7 +367,7 @@ def compute_codomain_kohel(E, kernel, degree): psi_quo = poly_ring(psi/psi_2tor) if (0 != psi_quo.degree()): - raise ArithmeticError, "For basic Kohel's algorithm, if the kernel degree is even then the kernel must be contained in the two torsion." + raise ArithmeticError("For basic Kohel's algorithm, if the kernel degree is even then the kernel must be contained in the two torsion.") n = psi_2tor.degree() @@ -873,7 +873,7 @@ def __init__(self, E, kernel, codomain=None, degree=None, model=None, check=True """ if not is_EllipticCurve(E): - raise ValueError, "E parameter must be an EllipticCurve." + raise ValueError("E parameter must be an EllipticCurve.") if type(kernel) != type([1,1]) and kernel in E : # a single point was given, we put it in a list @@ -890,7 +890,7 @@ def __init__(self, E, kernel, codomain=None, degree=None, model=None, check=True if (kernel is None) and (codomain is not None): if (degree is None): - raise ValueError, "If specifying isogeny by domain and codomain, degree parameter must be set." + raise ValueError("If specifying isogeny by domain and codomain, degree parameter must be set.") # save the domain/codomain: really used now (trac #7096) old_domain = E @@ -982,7 +982,7 @@ def __call__(self, P, output_base_ring=None): # is an extension of this ring if (E1 != E_P): if (E1.a_invariants() != E_P.a_invariants()) : - raise ValueError, "P must be on a curve with same Weierstrass model as the domain curve of this isogeny." + raise ValueError("P must be on a curve with same Weierstrass model as the domain curve of this isogeny.") change_output_ring = True @@ -992,7 +992,7 @@ def __call__(self, P, output_base_ring=None): (xP, yP) = P.xy() if not self.__E1.is_on_curve(xP,yP): - raise InputError, "Input point must be on the domain curve of this isogeny." + raise InputError("Input point must be on the domain curve of this isogeny.") # if there is a pre isomorphism, apply it if (self.__pre_isomorphism is not None): @@ -1483,7 +1483,7 @@ def __init_kernel_polynomial(self): if ("velu" == self.__algorithm): ker_poly_list = self.__init_kernel_polynomial_velu() else: - raise InputError, "The kernel polynomial should already be defined!" + raise InputError("The kernel polynomial should already be defined!") return ker_poly_list @@ -1621,25 +1621,25 @@ def __setup_post_isomorphism(self, codomain, model): if (model is not None): if (codomain is not None): - raise ValueError, "Cannot specify a codomain and model flag simultaneously." + raise ValueError("Cannot specify a codomain and model flag simultaneously.") if ('minimal' == model): if (not is_RationalField(oldE2.base_field())): - raise ValueError, "specifying minimal for model flag only valid with curves over the rational numbers." + raise ValueError("specifying minimal for model flag only valid with curves over the rational numbers.") newE2 = oldE2.minimal_model() post_isom = oldE2.isomorphism_to(newE2) else: - raise ValueError, "Unknown value of model flag." + raise ValueError("Unknown value of model flag.") elif (codomain is not None): if (not is_EllipticCurve(codomain)): - raise ValueError, "Codomain parameter must be an elliptic curve." + raise ValueError("Codomain parameter must be an elliptic curve.") if (not oldE2.is_isomorphic(codomain)): - raise ValueError, "Codomain parameter must be isomorphic to computed codomain isogeny" + raise ValueError("Codomain parameter must be isomorphic to computed codomain isogeny") newE2 = codomain post_isom = oldE2.isomorphism_to(newE2) @@ -1676,7 +1676,7 @@ def __init_from_kernel_list(self, kernel_gens): if self.__check : for P in kernel_gens: if not P.has_finite_order(): - raise ValueError, "The points in the kernel must be of finite order." + raise ValueError("The points in the kernel must be of finite order.") # work around the current implementation of torsion points. When they are done better this could be # reduced but it won't speed things up too much. kernel_list = Set([self.__E1(0)]) @@ -2034,7 +2034,7 @@ def __init_from_kernel_polynomial(self, kernel_polynomial, degree=None): n = len(kernel_polynomial)-1 if kernel_polynomial[-1] != 1: - raise ValueError, "The kernel polynomial must be monic." + raise ValueError("The kernel polynomial must be monic.") self.__kernel_polynomial_list = kernel_polynomial @@ -2056,7 +2056,7 @@ def __init_from_kernel_polynomial(self, kernel_polynomial, degree=None): psi_quo = poly_ring(psi/psi_G) if (0 != psi_quo.degree()): - raise NotImplementedError, "For basic Kohel's algorithm, if the kernel degree is even then the kernel must be contained in the two torsion." + raise NotImplementedError("For basic Kohel's algorithm, if the kernel degree is even then the kernel must be contained in the two torsion.") (phi, omega, v, w, n, d) = self.__init_even_kernel_polynomial(E, psi_G) @@ -2134,7 +2134,7 @@ def __init_even_kernel_polynomial(self, E, psi_G): #check if the polynomial really divides the two_torsion_polynomial if self.__check and E.division_polynomial(2, x=self.__x_var) % psi_G != 0 : - raise ValueError, "The polynomial does not define a finite subgroup of the elliptic curve." + raise ValueError("The polynomial does not define a finite subgroup of the elliptic curve.") n = psi_G.degree() d = n+1 @@ -2187,7 +2187,7 @@ def __init_even_kernel_polynomial(self, E, psi_G): (v,w) = compute_vw_kohel_even_deg3(b2,b4,s1,s2,s3) else: - raise ValueError, "input polynomial must be of degree 1 or 3, not %d" % n + raise ValueError("input polynomial must be of degree 1 or 3, not %d" % n) return (phi, omega, v, w, n, d) @@ -2242,7 +2242,7 @@ def __init_odd_kernel_polynomial(self, E, psi): if self.__check: alpha = psi.parent().quotient(psi).gen() if not E.division_polynomial(d, x=alpha).is_zero(): - raise ValueError, "The polynomial does not define a finite subgroup of the elliptic curve." + raise ValueError("The polynomial does not define a finite subgroup of the elliptic curve.") x = self.__x_var @@ -2782,10 +2782,10 @@ def set_pre_isomorphism(self, preWI): WIcod = preWI.codomain().codomain() if (type(preWI) != WeierstrassIsomorphism): - raise ValueError, "Invalid parameter: isomorphism must be of type Weierstrass isomorphism." + raise ValueError("Invalid parameter: isomorphism must be of type Weierstrass isomorphism.") if (self.__E1 != WIcod): - raise ValueError, "Invalid parameter: isomorphism must have codomain curve equal to this isogenies' domain." + raise ValueError("Invalid parameter: isomorphism must have codomain curve equal to this isogenies' domain.") if (self.__pre_isomorphism is None): isom = preWI @@ -2846,10 +2846,10 @@ def set_post_isomorphism(self, postWI): WIcod = postWI.codomain().codomain() if (type(postWI) != WeierstrassIsomorphism): - raise ValueError, "Invalid parameter: isomorphism must be of type Weierstrass isomorphism." + raise ValueError("Invalid parameter: isomorphism must be of type Weierstrass isomorphism.") if (self.__E2 != WIdom): - raise ValueError, "Invalid parameter: isomorphism must have domain curve equal to this isogenies' codomain." + raise ValueError("Invalid parameter: isomorphism must have domain curve equal to this isogenies' codomain.") if (self.__post_isomorphism is None): isom = postWI @@ -3244,7 +3244,7 @@ def dual(self): # trac 7096 if F(d) == 0: - raise NotImplementedError, "The dual isogeny is not separable, but only separable isogenies are implemented so far" + raise NotImplementedError("The dual isogeny is not separable, but only separable isogenies are implemented so far") # trac 7096 # this should take care of the case when the isogeny is not normalized. @@ -3280,7 +3280,7 @@ def dual(self): auts = phi_hat.codomain().automorphsims() aut = [a for a in auts if a.u == sc] if len(aut) != 1: - raise ValueError, "There is a bug in dual()." + raise ValueError("There is a bug in dual().") phi_hat.set_post_isomorphism(a[0]) self.__dual = phi_hat @@ -3487,7 +3487,7 @@ def n(self): NotImplementedError: Numerical approximations do not make sense for Elliptic Curve Isogenies """ - raise NotImplementedError, "Numerical approximations do not make sense for Elliptic Curve Isogenies" + raise NotImplementedError("Numerical approximations do not make sense for Elliptic Curve Isogenies") # no longer needed (trac 7096) # def starks_find_r_and_t(T, Z): diff --git a/src/sage/schemes/elliptic_curves/ell_egros.py b/src/sage/schemes/elliptic_curves/ell_egros.py index 355139239e3..67486fe005c 100644 --- a/src/sage/schemes/elliptic_curves/ell_egros.py +++ b/src/sage/schemes/elliptic_curves/ell_egros.py @@ -377,7 +377,7 @@ def egros_get_j(S=[], proof=None, verbose=False): """ if not all([p.is_prime() for p in S]): - raise ValueError, "Elements of S must be prime." + raise ValueError("Elements of S must be prime.") if proof is None: from sage.structure.proof.proof import get_flag diff --git a/src/sage/schemes/elliptic_curves/ell_field.py b/src/sage/schemes/elliptic_curves/ell_field.py index e81fc129d92..3815d8079b5 100644 --- a/src/sage/schemes/elliptic_curves/ell_field.py +++ b/src/sage/schemes/elliptic_curves/ell_field.py @@ -141,15 +141,15 @@ def quadratic_twist(self, D=None): while len((x**2-D).roots())>0: D = K.random_element() else: - raise ValueError, "twisting parameter D must be specified over infinite fields." + raise ValueError("twisting parameter D must be specified over infinite fields.") else: try: D=K(D) except ValueError: - raise ValueError, "twisting parameter D must be in the base field." + raise ValueError("twisting parameter D must be in the base field.") if char!=2 and D.is_zero(): - raise ValueError, "twisting parameter D must be nonzero when characteristic is not 2" + raise ValueError("twisting parameter D must be nonzero when characteristic is not 2") if char!=2: b2,b4,b6,b8=self.b_invariants() @@ -166,7 +166,7 @@ def quadratic_twist(self, D=None): assert E0.a4()==K(0) return EllipticCurve(K,[1,E0.a2()+D,0,0,E0.a6()]) else: - raise ValueError, "Quadratic twist not implemented in char 2 when j=0" + raise ValueError("Quadratic twist not implemented in char 2 when j=0") def two_torsion_rank(self): r""" @@ -236,13 +236,13 @@ def quartic_twist(self, D): D=K(D) if char==2 or char==3: - raise ValueError, "Quartic twist not defined in chars 2,3" + raise ValueError("Quartic twist not defined in chars 2,3") if self.j_invariant() !=K(1728): - raise ValueError, "Quartic twist not defined when j!=1728" + raise ValueError("Quartic twist not defined when j!=1728") if D.is_zero(): - raise ValueError, "quartic twist requires a nonzero argument" + raise ValueError("quartic twist requires a nonzero argument") c4,c6=self.c_invariants() # E is isomorphic to [0,0,0,-27*c4,0] @@ -281,13 +281,13 @@ def sextic_twist(self, D): D=K(D) if char==2 or char==3: - raise ValueError, "Sextic twist not defined in chars 2,3" + raise ValueError("Sextic twist not defined in chars 2,3") if self.j_invariant() !=K(0): - raise ValueError, "Sextic twist not defined when j!=0" + raise ValueError("Sextic twist not defined when j!=0") if D.is_zero(): - raise ValueError, "Sextic twist requires a nonzero argument" + raise ValueError("Sextic twist requires a nonzero argument") c4,c6=self.c_invariants() # E is isomorphic to [0,0,0,0,-54*c6] @@ -389,7 +389,7 @@ def is_quadratic_twist(self, other): E = self F = other if not is_EllipticCurve(E) or not is_EllipticCurve(F): - raise ValueError, "arguments are not elliptic curves" + raise ValueError("arguments are not elliptic curves") K = E.base_ring() zero = K.zero_element() if not K == F.base_ring(): @@ -406,10 +406,10 @@ def is_quadratic_twist(self, other): char=K.characteristic() if char==2: - raise NotImplementedError, "not implemented in characteristic 2" + raise NotImplementedError("not implemented in characteristic 2") elif char==3: if j==0: - raise NotImplementedError, "not implemented in characteristic 3 for curves of j-invariant 0" + raise NotImplementedError("not implemented in characteristic 3 for curves of j-invariant 0") D = E.b2()/F.b2() else: @@ -488,7 +488,7 @@ def is_quartic_twist(self, other): E = self F = other if not is_EllipticCurve(E) or not is_EllipticCurve(F): - raise ValueError, "arguments are not elliptic curves" + raise ValueError("arguments are not elliptic curves") K = E.base_ring() zero = K.zero_element() if not K == F.base_ring(): @@ -503,9 +503,9 @@ def is_quartic_twist(self, other): char=K.characteristic() if char==2: - raise NotImplementedError, "not implemented in characteristic 2" + raise NotImplementedError("not implemented in characteristic 2") elif char==3: - raise NotImplementedError, "not implemented in characteristic 3" + raise NotImplementedError("not implemented in characteristic 3") else: # now char!=2,3: D = F.c4()/E.c4() @@ -557,7 +557,7 @@ def is_sextic_twist(self, other): E = self F = other if not is_EllipticCurve(E) or not is_EllipticCurve(F): - raise ValueError, "arguments are not elliptic curves" + raise ValueError("arguments are not elliptic curves") K = E.base_ring() zero = K.zero_element() if not K == F.base_ring(): @@ -572,9 +572,9 @@ def is_sextic_twist(self, other): char=K.characteristic() if char==2: - raise NotImplementedError, "not implemented in characteristic 2" + raise NotImplementedError("not implemented in characteristic 2") elif char==3: - raise NotImplementedError, "not implemented in characteristic 3" + raise NotImplementedError("not implemented in characteristic 3") else: # now char!=2,3: D = F.c6()/E.c6() @@ -638,7 +638,7 @@ def descend_to(self, K, f=None): None """ if not K.is_field(): - raise TypeError, "Input must be a field." + raise TypeError("Input must be a field.") if self.base_field()==K: return self j = self.j_invariant() @@ -652,7 +652,7 @@ def descend_to(self, K, f=None): elif f == None: embeddings = K.embeddings(self.base_field()) if len(embeddings) == 0: - raise TypeError, "Input must be a subfield of the base field of the curve." + raise TypeError("Input must be a subfield of the base field of the curve.") for g in embeddings: try: jbase = g.preimage(j) @@ -939,11 +939,11 @@ def isogenies_prime_degree(self, l=None, max_l=31): """ F = self.base_ring() if is_RealField(F): - raise NotImplementedError, "This code could be implemented for general real fields, but has not been yet." + raise NotImplementedError("This code could be implemented for general real fields, but has not been yet.") if is_ComplexField(F): - raise NotImplementedError, "This code could be implemented for general complex fields, but has not been yet." + raise NotImplementedError("This code could be implemented for general complex fields, but has not been yet.") if F == rings.QQbar: - raise NotImplementedError, "This code could be implemented for QQbar, but has not been yet." + raise NotImplementedError("This code could be implemented for QQbar, but has not been yet.") from isogeny_small_degree import isogenies_prime_degree if l is None: @@ -954,17 +954,17 @@ def isogenies_prime_degree(self, l=None, max_l=31): try: l = rings.ZZ(l) except TypeError: - raise ValueError, "%s is not prime."%l + raise ValueError("%s is not prime."%l) if l.is_prime(): return isogenies_prime_degree(self, l) else: - raise ValueError, "%s is not prime."%l + raise ValueError("%s is not prime."%l) L = list(set(l)) try: L = [rings.ZZ(l) for l in L] except TypeError: - raise ValueError, "%s is not a list of primes."%l + raise ValueError("%s is not a list of primes."%l) L.sort() return sum([isogenies_prime_degree(self,l) for l in L],[]) @@ -1016,11 +1016,11 @@ def is_isogenous(self, other, field=None): """ from ell_generic import is_EllipticCurve if not is_EllipticCurve(other): - raise ValueError, "Second argument is not an Elliptic Curve." + raise ValueError("Second argument is not an Elliptic Curve.") if self.is_isomorphic(other): return True else: - raise NotImplementedError, "Only implemented for isomorphic curves over general fields." + raise NotImplementedError("Only implemented for isomorphic curves over general fields.") def weierstrass_p(self, prec=20, algorithm=None): r""" diff --git a/src/sage/schemes/elliptic_curves/ell_finite_field.py b/src/sage/schemes/elliptic_curves/ell_finite_field.py index d860dcae6a9..d5b2b3f5e97 100644 --- a/src/sage/schemes/elliptic_curves/ell_finite_field.py +++ b/src/sage/schemes/elliptic_curves/ell_finite_field.py @@ -276,10 +276,10 @@ def count_points(self, n=1): try: n = Integer(n) except TypeError: - raise TypeError, "n must be a positive integer" + raise TypeError("n must be a positive integer") if n<1: - raise ValueError, "n must be a positive integer" + raise ValueError("n must be a positive integer") if n==1: return self.cardinality() @@ -898,9 +898,9 @@ def cardinality(self, algorithm='heuristic', extension_degree=1): if N1 == N2: N = N1 else: - raise RuntimeError, "BUG! Cardinality with pari=%s but with bsgs=%s"%(N1, N2) + raise RuntimeError("BUG! Cardinality with pari=%s but with bsgs=%s"%(N1, N2)) else: - raise ValueError, "Algorithm is not known" + raise ValueError("Algorithm is not known") self._order = Integer(N) return self._order @@ -1079,7 +1079,7 @@ def cardinality_pari(self): if k.degree()==1: return ZZ(p + 1 - int(self._pari_().ellap(p))) else: - raise ValueError, "cardinality_pari() only works over prime fields." + raise ValueError("cardinality_pari() only works over prime fields.") def cardinality_bsgs(self, verbose=False): r""" @@ -1670,11 +1670,11 @@ def is_isogenous(self, other, field=None, proof=True): """ from ell_generic import is_EllipticCurve if not is_EllipticCurve(other): - raise ValueError, "Second argument is not an Elliptic Curve." + raise ValueError("Second argument is not an Elliptic Curve.") if self.is_isomorphic(other): return True elif self.base_field().characteristic() != other.base_field().characteristic(): - raise ValueError, "The base fields must have the same characteristic." + raise ValueError("The base fields must have the same characteristic.") elif field==None: if self.base_field().degree() == other.base_field().degree(): if self.cardinality() == other.cardinality(): @@ -1692,10 +1692,10 @@ def is_isogenous(self, other, field=None, proof=True): else: return False else: - raise ValueError, "Curves have different base fields: use the field parameter." + raise ValueError("Curves have different base fields: use the field parameter.") else: if not lcm(self.base_field().degree(), other.base_field().degree()).divides(field.degree()): - raise ValueError, "Field must be an extension of the base fields of both curves" + raise ValueError("Field must be an extension of the base fields of both curves") else: if \ self.cardinality(extension_degree=field.degree()//self.base_field().degree())\ @@ -1949,9 +1949,9 @@ def supersingular_j_polynomial(p): try: p = ZZ(p) except TypeError: - raise ValueError, "p (=%s) should be a prime number"%p + raise ValueError("p (=%s) should be a prime number"%p) if not p.is_prime(): - raise ValueError, "p (=%s) should be a prime number"%p + raise ValueError("p (=%s) should be a prime number"%p) J = polygen(GF(p),'j') if p<13: @@ -2085,7 +2085,7 @@ def is_j_supersingular(j, proof=True): """ if not is_FiniteFieldElement(j): - raise ValueError, "%s must be an element of a finite field"%j + raise ValueError("%s must be an element of a finite field"%j) F = j.parent() p = F.characteristic() diff --git a/src/sage/schemes/elliptic_curves/ell_generic.py b/src/sage/schemes/elliptic_curves/ell_generic.py index ba6fcf615c4..c90e28e568d 100644 --- a/src/sage/schemes/elliptic_curves/ell_generic.py +++ b/src/sage/schemes/elliptic_curves/ell_generic.py @@ -153,8 +153,7 @@ def __init__(self, ainvs, extra=None): ainvs = [K(0),K(0),K(0)] + ainvs self.__ainvs = tuple(ainvs) if self.discriminant() == 0: - raise ArithmeticError, \ - "Invariants %s define a singular curve."%ainvs + raise ArithmeticError("Invariants %s define a singular curve."%ainvs) PP = projective_space.ProjectiveSpace(2, K, names='xyz'); x, y, z = PP.coordinate_ring().gens() a1, a2, a3, a4, a6 = ainvs @@ -704,7 +703,7 @@ def is_x_coord(self, x): try: x = K(x) except TypeError: - raise TypeError, 'x must be coercible into the base ring of the curve' + raise TypeError('x must be coercible into the base ring of the curve') a1, a2, a3, a4, a6 = self.ainvs() fx = ((x + a2) * x + a4) * x + a6 if a1.is_zero() and a3.is_zero(): @@ -836,7 +835,7 @@ def lift_x(self, x, all=False): if all: return [] else: - raise ValueError, "No point with x-coordinate %s on %s"%(x, self) + raise ValueError("No point with x-coordinate %s on %s"%(x, self)) def _point_homset(self, *args, **kwds): r""" @@ -864,7 +863,7 @@ def __getitem__(self, n): ... NotImplementedError: not implemented. """ - raise NotImplementedError, "not implemented." + raise NotImplementedError("not implemented.") def __is_over_RationalField(self): r""" @@ -1302,7 +1301,7 @@ def gens(self): sage: E.gens() [(0 : 1 : 1)] """ - raise NotImplementedError, "not implemented." + raise NotImplementedError("not implemented.") def gen(self, i): r""" @@ -1637,7 +1636,7 @@ def division_polynomial_0(self, n, x=None, cache=None): (6*x**2 + b2*x + b4) * \ self.division_polynomial_0(3, x, cache) else: - raise ValueError, "n must be a positive integer (or -1 or -2)" + raise ValueError("n must be a positive integer (or -1 or -2)") else: if n % 2 == 0: m = (n-2) // 2 @@ -1783,7 +1782,7 @@ def division_polynomial(self, m, x=None, two_torsion_multiplicity=2): """ if not two_torsion_multiplicity in [0,1,2]: - raise ValueError, "two_torsion_multiplicity must be 0,1 or 2" + raise ValueError("two_torsion_multiplicity must be 0,1 or 2") # Coerce the input m to be an integer m = rings.Integer(m) @@ -1821,7 +1820,7 @@ def division_polynomial(self, m, x=None, two_torsion_multiplicity=2): self.__divpoly1[(m,xy)] = fxy return fxy else: - raise ValueError, "x should be a tuple of length 2 (or None) when two_torsion_multiplicity is 1" + raise ValueError("x should be a tuple of length 2 (or None) when two_torsion_multiplicity is 1") if two_torsion_multiplicity == 2: try: @@ -2466,13 +2465,13 @@ def short_weierstrass_model(self, complete_cube=True): # any curve of the form y^2 = x^3 +.. is singular in characteristic 2 if K.characteristic() == 2: - raise ValueError, "short_weierstrass_model(): no short model for %s (characteristic is %s)"%(self,K.characteristic()) + raise ValueError("short_weierstrass_model(): no short model for %s (characteristic is %s)"%(self,K.characteristic())) # in characteristic 3 we can complete the square but we can only complete the cube if b2 is 0 if K.characteristic() == 3: b2,b4,b6,_ = self.b_invariants() if complete_cube and b2 != 0: - raise ValueError, "short_weierstrass_model(): no short model for %s (characteristic is %s)"%(self,K.characteristic()) + raise ValueError("short_weierstrass_model(): no short model for %s (characteristic is %s)"%(self,K.characteristic())) else: return constructor.EllipticCurve([0,b2,0,8*b4,16*b6]) @@ -2564,7 +2563,7 @@ def plot(self, xmin=None, xmax=None, components='both', **args): try: RR._coerce_(K(1)) except TypeError: - raise NotImplementedError, "Plotting of curves over %s not implemented yet"%K + raise NotImplementedError("Plotting of curves over %s not implemented yet"%K) if components not in ['both', 'bounded', 'unbounded']: raise ValueError("component must be one of 'both', 'bounded' or 'unbounded'") diff --git a/src/sage/schemes/elliptic_curves/ell_local_data.py b/src/sage/schemes/elliptic_curves/ell_local_data.py index 7118a2dbb8d..3bc26f741ef 100644 --- a/src/sage/schemes/elliptic_curves/ell_local_data.py +++ b/src/sage/schemes/elliptic_curves/ell_local_data.py @@ -255,7 +255,7 @@ def __init__(self, E, P, proof=None, algorithm="pari", globally=False): K = E.base_field() p = check_prime(K,P) # error handling done in that function if algorithm != "pari" and algorithm != "generic": - raise ValueError, "algorithm must be one of 'pari', 'generic'" + raise ValueError("algorithm must be one of 'pari', 'generic'") self._reduction_type = None if K is QQ: @@ -372,7 +372,7 @@ def minimal_model(self, reduce=True): try: return self._Emin except AttributeError: - raise ValueError, "the argument reduce must not be False if algorithm=pari is used" + raise ValueError("the argument reduce must not be False if algorithm=pari is used") def prime(self): """ @@ -838,14 +838,14 @@ def _pcubicroots(b, c, d): (a1, a2, a3, a4, a6) = C.a_invariants() (b2, b4, b6, b8) = C.b_invariants() if min([pval(a) for a in (a1, a2, a3, a4, a6) if a != 0]) < 0: - raise RuntimeError, "Non-integral model after first transform!" + raise RuntimeError("Non-integral model after first transform!") verbose("After first transform %s\n, [a1,a2,a3,a4,a6] = %s\n, valuations = %s"%([r, 0, t], [a1, a2, a3, a4, a6], [pval(a1), pval(a2), pval(a3), pval(a4), pval(a6)]), t, 2) if pval(a3) == 0: - raise RuntimeError, "p does not divide a3 after first transform!" + raise RuntimeError("p does not divide a3 after first transform!") if pval(a4) == 0: - raise RuntimeError, "p does not divide a4 after first transform!" + raise RuntimeError("p does not divide a4 after first transform!") if pval(a6) == 0: - raise RuntimeError, "p does not divide a6 after first transform!" + raise RuntimeError("p does not divide a6 after first transform!") # Now we test for Types In, II, III, IV # NB the c invariants never change. @@ -904,17 +904,17 @@ def _pcubicroots(b, c, d): (b2, b4, b6, b8) = C.b_invariants() verbose("After second transform %s\n[a1, a2, a3, a4, a6] = %s\nValuations: %s"%([0, s, t], [a1,a2,a3,a4,a6],[pval(a1),pval(a2),pval(a3),pval(a4),pval(a6)]), t, 2) if pval(a1) == 0: - raise RuntimeError, "p does not divide a1 after second transform!" + raise RuntimeError("p does not divide a1 after second transform!") if pval(a2) == 0: - raise RuntimeError, "p does not divide a2 after second transform!" + raise RuntimeError("p does not divide a2 after second transform!") if pval(a3) < 2: - raise RuntimeError, "p^2 does not divide a3 after second transform!" + raise RuntimeError("p^2 does not divide a3 after second transform!") if pval(a4) < 2: - raise RuntimeError, "p^2 does not divide a4 after second transform!" + raise RuntimeError("p^2 does not divide a4 after second transform!") if pval(a6) < 3: - raise RuntimeError, "p^3 does not divide a6 after second transform!" + raise RuntimeError("p^3 does not divide a6 after second transform!") if min(pval(a1), pval(a2), pval(a3), pval(a4), pval(a6)) < 0: - raise RuntimeError, "Non-integral model after second transform!" + raise RuntimeError("Non-integral model after second transform!") # Analyze roots of the cubic T^3 + bT^2 + cT + d = 0 mod P, where # b = a2/p, c = a4/p^2, d = a6/p^3 @@ -1018,9 +1018,9 @@ def _pcubicroots(b, c, d): (b2, b4, b6, b8) = C.b_invariants() verbose("After third transform %s\n[a1,a2,a3,a4,a6] = %s\nValuations: %s"%([r,0,0],[a1,a2,a3,a4,a6],[pval(ai) for ai in [a1,a2,a3,a4,a6]]), t, 2) if min(pval(ai) for ai in [a1,a2,a3,a4,a6]) < 0: - raise RuntimeError, "Non-integral model after third transform!" + raise RuntimeError("Non-integral model after third transform!") if pval(a2) < 2 or pval(a4) < 3 or pval(a6) < 4: - raise RuntimeError, "Cubic after transform does not have a triple root at 0" + raise RuntimeError("Cubic after transform does not have a triple root at 0") a3t = preduce(a3/pi2) a6t = preduce(a6/pi4) # We test for Type IV* @@ -1109,29 +1109,29 @@ def check_prime(K,P): if P.is_prime(): return P else: - raise TypeError, "%s is not prime"%P + raise TypeError("%s is not prime"%P) else: if is_Ideal(P) and P.base_ring() is ZZ and P.is_prime(): return P.gen() - raise TypeError, "%s is not a prime ideal of %s"%(P,ZZ) + raise TypeError("%s is not a prime ideal of %s"%(P,ZZ)) if not is_NumberField(K): - raise TypeError, "%s is not a number field"%K + raise TypeError("%s is not a number field"%K) if is_NumberFieldFractionalIdeal(P): if P.is_prime(): return P else: - raise TypeError, "%s is not a prime ideal of %s"%(P,K) + raise TypeError("%s is not a prime ideal of %s"%(P,K)) if is_NumberFieldElement(P): if P in K: P = K.ideal(P) else: - raise TypeError, "%s is not an element of %s"%(P,K) + raise TypeError("%s is not an element of %s"%(P,K)) if P.is_prime(): return P else: - raise TypeError, "%s is not a prime ideal of %s"%(P,K) + raise TypeError("%s is not a prime ideal of %s"%(P,K)) - raise TypeError, "%s is not a valid prime of %s"%(P,K) + raise TypeError("%s is not a valid prime of %s"%(P,K)) diff --git a/src/sage/schemes/elliptic_curves/ell_modular_symbols.py b/src/sage/schemes/elliptic_curves/ell_modular_symbols.py index 7d2a6d3a1bf..06a591b9ccf 100644 --- a/src/sage/schemes/elliptic_curves/ell_modular_symbols.py +++ b/src/sage/schemes/elliptic_curves/ell_modular_symbols.py @@ -96,9 +96,9 @@ def modular_symbol_space(E, sign, base_ring, bound=None): """ _sign = int(sign) if _sign != sign: - raise TypeError, 'sign must be an integer' + raise TypeError('sign must be an integer') if not (_sign in [-1,0,1]): - raise TypeError, 'sign must -1, 0, or 1' + raise TypeError('sign must -1, 0, or 1') N = E.conductor() M = ModularSymbols(N, sign=sign, base_ring=base_ring) if bound is None: @@ -488,11 +488,11 @@ def __init__(self, E, sign, normalize="L_ratio"): """ self._sign = ZZ(sign) if self._sign != sign: - raise TypeError, 'sign must be an integer' + raise TypeError('sign must be an integer') if self._sign != -1 and self._sign != 1: - raise TypeError, 'sign must -1 or 1' + raise TypeError('sign must -1 or 1') if self._sign == -1: - raise NotImplementedError, "Despite that eclib has now -1 modular symbols the interface to them is not yet written." + raise NotImplementedError("Despite that eclib has now -1 modular symbols the interface to them is not yet written.") self._E = E self._use_eclib = True self._base_ring = QQ @@ -509,7 +509,7 @@ def __init__(self, E, sign, normalize="L_ratio"): elif normalize == "none": self._scaling = ZZ(1) else : - raise ValueError, "no normalization '%s' known for modular symbols using John Cremona's eclib"%normalize + raise ValueError("no normalization '%s' known for modular symbols using John Cremona's eclib"%normalize) def _call_with_caching(self, r): @@ -619,9 +619,9 @@ def __init__(self, E, sign, normalize="L_ratio"): """ self._sign = ZZ(sign) if self._sign != sign: - raise TypeError, 'sign must be an integer' + raise TypeError('sign must be an integer') if self._sign != -1 and self._sign != 1: - raise TypeError, 'sign must -1 or 1' + raise TypeError('sign must -1 or 1') self._E = E self._use_eclib = False self._normalize = normalize @@ -642,7 +642,7 @@ def __init__(self, E, sign, normalize="L_ratio"): self._scaling = 1 self._e = self._modsym.dual_eigenvector() else : - raise ValueError, "no normalization %s known for modular symbols"%normalize + raise ValueError("no normalization %s known for modular symbols"%normalize) def _find_scaling_period(self): diff --git a/src/sage/schemes/elliptic_curves/ell_number_field.py b/src/sage/schemes/elliptic_curves/ell_number_field.py index 6582830a866..48c7a8619fd 100644 --- a/src/sage/schemes/elliptic_curves/ell_number_field.py +++ b/src/sage/schemes/elliptic_curves/ell_number_field.py @@ -1580,7 +1580,7 @@ def global_minimal_model(self, proof = None): proof = sage.structure.proof.proof.get_flag(None, "number_field") K = self.base_ring() if K.class_number() != 1: - raise ValueError, "global minimal models only exist in general for class number 1" + raise ValueError("global minimal models only exist in general for class number 1") E = self.global_integral_model() primes = E.base_ring()(E.discriminant()).support() @@ -1625,16 +1625,16 @@ def reduction(self,place): try: place = K.ideal(place) except TypeError: - raise TypeError, "The parameter must be an ideal of the base field of the elliptic curve" + raise TypeError("The parameter must be an ideal of the base field of the elliptic curve") if not place.is_prime(): - raise ValueError, "The ideal must be prime." + raise ValueError("The ideal must be prime.") disc = self.discriminant() if not K.ideal(disc).valuation(place) == 0: local_data=self.local_data(place) if local_data.has_good_reduction(): Fv = OK.residue_field(place) return local_data.minimal_model().change_ring(Fv) - raise ValueError, "The curve must have good reduction at the place." + raise ValueError("The curve must have good reduction at the place.") Fv = OK.residue_field(place) return self.change_ring(Fv) @@ -2027,7 +2027,7 @@ def rank(self,verbose=0, lim1=2, lim3=4, limtriv=2, maxprob=20, limbigprime=30): if lower == upper: return lower else: - raise ValueError, 'There is insufficient data to determine the rank - 2-descent gave lower bound %s and upper bound %s' % (lower, upper) + raise ValueError('There is insufficient data to determine the rank - 2-descent gave lower bound %s and upper bound %s' % (lower, upper)) def gens(self,verbose=0, lim1=2, lim3=4, limtriv=2, maxprob=20, limbigprime=30): r""" @@ -2304,12 +2304,12 @@ def is_isogenous(self, other, proof=True, maxnorm=100): """ if not is_EllipticCurve(other): - raise ValueError, "Second argument is not an Elliptic Curve." + raise ValueError("Second argument is not an Elliptic Curve.") if self.is_isomorphic(other): return True K = self.base_field() if K != other.base_field(): - raise ValueError, "Second argument must be defined over the same number field." + raise ValueError("Second argument must be defined over the same number field.") E1 = self.integral_model() E2 = other.integral_model() @@ -2350,7 +2350,7 @@ def is_isogenous(self, other, proof=True, maxnorm=100): # At this point is is highly likely that the curves are # isogenous, but we have not proved it. - raise NotImplementedError, "Curves appear to be isogenous (same conductor, isogenous modulo all primes of norm up to %s), but no isogeny has been constructed." % (10*maxnorm) + raise NotImplementedError("Curves appear to be isogenous (same conductor, isogenous modulo all primes of norm up to %s), but no isogeny has been constructed." % (10*maxnorm)) def isogeny_degree(self, other): """ diff --git a/src/sage/schemes/elliptic_curves/ell_padic_field.py b/src/sage/schemes/elliptic_curves/ell_padic_field.py index 5946698ba6d..9ca4d8d94d5 100644 --- a/src/sage/schemes/elliptic_curves/ell_padic_field.py +++ b/src/sage/schemes/elliptic_curves/ell_padic_field.py @@ -92,7 +92,7 @@ def frobenius(self, P=None): a1, a2, a3, a4, a6 = self.a_invariants() if a1 != 0 or a2 != 0: - raise NotImplementedError, "Curve must be in weierstrass normal form." + raise NotImplementedError("Curve must be in weierstrass normal form.") f = x*x*x + a2*x*x + a4*x + a6 h = (f(x**p) - f**p) diff --git a/src/sage/schemes/elliptic_curves/ell_rational_field.py b/src/sage/schemes/elliptic_curves/ell_rational_field.py index 86a7516ed79..e934bbd222f 100644 --- a/src/sage/schemes/elliptic_curves/ell_rational_field.py +++ b/src/sage/schemes/elliptic_curves/ell_rational_field.py @@ -219,7 +219,7 @@ def __init__(self, ainvs, extra=None): return EllipticCurve_number_field.__init__(self, Q, ainvs) if self.base_ring() != Q: - raise TypeError, "Base field (=%s) must be the Rational Field."%self.base_ring() + raise TypeError("Base field (=%s) must be the Rational Field."%self.base_ring()) def _set_rank(self, r): """ @@ -385,7 +385,7 @@ def is_p_integral(self, p): True """ if not arith.is_prime(p): - raise ArithmeticError, "p must be prime" + raise ArithmeticError("p must be prime") if self.is_integral(): return True return bool(misc.mul([x.valuation(p) >= 0 for x in self.ainvs()])) @@ -576,11 +576,11 @@ def conductor(self, algorithm="pari"): N3 = self.conductor("gp") N4 = self.conductor("generic") if N1 != N2 or N2 != N3 or N2 != N4: - raise ArithmeticError, "PARI, mwrank, gp and Sage compute different conductors (%s,%s,%s,%3) for %s"%( - N1, N2, N3, N4, self) + raise ArithmeticError("PARI, mwrank, gp and Sage compute different conductors (%s,%s,%s,%3) for %s"%( + N1, N2, N3, N4, self)) return N1 else: - raise RuntimeError, "algorithm '%s' is not known."%algorithm + raise RuntimeError("algorithm '%s' is not known."%algorithm) #################################################################### # Access to PARI curves related to this curve. @@ -775,7 +775,7 @@ def database_curve(self): try: self.__database_curve = D.elliptic_curve_from_ainvs(ainvs) except RuntimeError: - raise RuntimeError, "Elliptic curve %s not in the database."%self + raise RuntimeError("Elliptic curve %s not in the database."%self) return self.__database_curve @@ -986,7 +986,7 @@ def anlist(self, n, python_ints=False): n = int(n) e = self.pari_mincurve() if n >= 2147483648: - raise RuntimeError, "anlist: n (=%s) must be < 2147483648."%n + raise RuntimeError("anlist: n (=%s) must be < 2147483648."%n) v = [0] + e.ellan(n, python_ints=True) if not python_ints: @@ -1368,20 +1368,20 @@ def analytic_rank(self, algorithm="pari", leading_coefficient=False): return rings.Integer(self.pari_curve().ellanalyticrank()[0]) elif algorithm == 'rubinstein': if leading_coefficient: - raise NotImplementedError, "Cannot compute leading coefficient using rubinstein algorithm" + raise NotImplementedError("Cannot compute leading coefficient using rubinstein algorithm") try: from sage.lfunctions.lcalc import lcalc return lcalc.analytic_rank(L=self) except TypeError as msg: - raise RuntimeError, "unable to compute analytic rank using rubinstein algorithm ('%s')"%msg + raise RuntimeError("unable to compute analytic rank using rubinstein algorithm ('%s')"%msg) elif algorithm == 'sympow': if leading_coefficient: - raise NotImplementedError, "Cannot compute leading coefficient using sympow" + raise NotImplementedError("Cannot compute leading coefficient using sympow") from sage.lfunctions.sympow import sympow return sympow.analytic_rank(self)[0] elif algorithm == 'magma': if leading_coefficient: - raise NotImplementedError, "Cannot compute leading coefficient using magma" + raise NotImplementedError("Cannot compute leading coefficient using magma") from sage.interfaces.all import magma return rings.Integer(magma(self).AnalyticRank()) elif algorithm == 'all': @@ -1391,10 +1391,10 @@ def analytic_rank(self, algorithm="pari", leading_coefficient=False): S = set([self.analytic_rank('pari'), self.analytic_rank('rubinstein'), self.analytic_rank('sympow')]) if len(S) != 1: - raise RuntimeError, "Bug in analytic_rank; algorithms don't agree! (E=%s)"%self + raise RuntimeError("Bug in analytic_rank; algorithms don't agree! (E=%s)"%self) return list(S)[0] else: - raise ValueError, "algorithm %s not defined"%algorithm + raise ValueError("algorithm %s not defined"%algorithm) def simon_two_descent(self, verbose=0, lim1=5, lim3=50, limtriv=3, maxprob=20, limbigprime=30): @@ -1724,7 +1724,7 @@ def rank(self, use_database=False, verbose=False, print "curve then trying this command again. You could also try rank" print "with only_use_mwrank=False." del E.__mwrank_curve - raise RuntimeError, 'Rank not provably correct.' + raise RuntimeError('Rank not provably correct.') else: misc.verbose("Warning -- rank not proven correct", level=1) self.__rank[proof] = r @@ -1735,7 +1735,7 @@ def rank(self, use_database=False, verbose=False, if proof: X= "".join(X.split("\n")[-4:-2]) print X - raise RuntimeError, 'Rank not provably correct.' + raise RuntimeError('Rank not provably correct.') else: misc.verbose("Warning -- rank not proven correct", level=1) @@ -1751,7 +1751,7 @@ def rank(self, use_database=False, verbose=False, match = 'found points of rank' i = X.find(match) if i == -1: - raise RuntimeError, "%s\nbug -- tried to find 'Rank =' or 'found points of rank' in mwrank output but couldn't."%X + raise RuntimeError("%s\nbug -- tried to find 'Rank =' or 'found points of rank' in mwrank output but couldn't."%X) j = i + X[i:].find('\n') r = Integer(X[i+len(match)+1:j]) self.__rank[proof] = r @@ -1927,8 +1927,8 @@ def gens(self, verbose=False, rank1_search=10, G = C.gens() if proof is True and C.certain() is False: del self.__mwrank_curve - raise RuntimeError, "Unable to compute the rank, hence generators, with certainty (lower bound=%s, generators found=%s). This could be because Sha(E/Q)[2] is nontrivial."%(C.rank(),G) + \ - "\nTry increasing descent_second_limit then trying this command again." + raise RuntimeError("Unable to compute the rank, hence generators, with certainty (lower bound=%s, generators found=%s). This could be because Sha(E/Q)[2] is nontrivial."%(C.rank(),G) + \ + "\nTry increasing descent_second_limit then trying this command again.") else: proof = C.certain() G = [[x*xterm,y*yterm,z] for x,y,z in G] @@ -1948,7 +1948,7 @@ def gens(self, verbose=False, rank1_search=10, if not 'The rank and full Mordell-Weil basis have been determined unconditionally' in X: msg = 'Generators not provably computed.' if proof: - raise RuntimeError, '%s\n%s'%(X,msg) + raise RuntimeError('%s\n%s'%(X,msg)) else: misc.verbose("Warning -- %s"%msg, level=1) elif proof is False: @@ -2173,7 +2173,7 @@ def saturation(self, points, verbose=False, max_prime=0, odd_primes_only=False): """ if not isinstance(points, list): - raise TypeError, "points (=%s) must be a list."%points + raise TypeError("points (=%s) must be a list."%points) if len(points) == 0: return [], None, R(1) @@ -2182,7 +2182,7 @@ def saturation(self, points, verbose=False, max_prime=0, odd_primes_only=False): if not isinstance(P, ell_point.EllipticCurvePoint_field): P = self(P) elif P.curve() != self: - raise ArithmeticError, "point (=%s) must be %s."%(P,self) + raise ArithmeticError("point (=%s) must be %s."%(P,self)) minimal = True if not self.is_minimal(): @@ -2268,7 +2268,7 @@ def CPS_height_bound(self): field. """ if not self.is_minimal(): - raise RuntimeError, "curve must be minimal." + raise RuntimeError("curve must be minimal.") return self.mwrank_curve().CPS_height_bound() @@ -2333,7 +2333,7 @@ def h_oo(x): elif algorithm == 'mwrank': return self.mwrank_curve().silverman_bound() else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) @@ -2542,7 +2542,7 @@ def ap(self, p): [-2, -3, -2, -1, -5, -2, 0, 0, 2, 6, -4, -1, -9, 2, -9] """ if not arith.is_prime(p): - raise ArithmeticError, "p must be prime" + raise ArithmeticError("p must be prime") return Integer(self.pari_mincurve().ellap(p)) def quadratic_twist(self, D): @@ -2633,7 +2633,7 @@ def is_p_minimal(self, p): [False, True, False, True, False, True, True, True, True] """ if not p.is_prime(): - raise ValueError,"p must be prime" + raise ValueError("p must be prime") if not self.is_p_integral(p): return False if p > 3: @@ -2698,7 +2698,7 @@ def kodaira_type_old(self, p): IV """ if not arith.is_prime(p): - raise ArithmeticError, "p must be prime" + raise ArithmeticError("p must be prime") try: self.__kodaira_type except AttributeError: @@ -2746,7 +2746,7 @@ def tamagawa_number_old(self, p): 3 """ if not arith.is_prime(p): - raise ArithmeticError, "p must be prime" + raise ArithmeticError("p must be prime") try: return self.__tamagawa_number[p] except (AttributeError, KeyError): @@ -2790,7 +2790,7 @@ def tamagawa_exponent(self, p): 4 """ if not arith.is_prime(p): - raise ArithmeticError, "p must be prime" + raise ArithmeticError("p must be prime") cp = self.tamagawa_number(p) if not cp==4: return cp @@ -3340,7 +3340,7 @@ def modular_degree(self, algorithm='sympow', M=1): from sage.interfaces.all import magma m = rings.Integer(magma(self).ModularDegree()) else: - raise ValueError, "unknown algorithm %s"%algorithm + raise ValueError("unknown algorithm %s"%algorithm) self.__modular_degree = m return m @@ -3474,7 +3474,7 @@ def congruence_number(self, M=1): self.__congruence_number = W.congruence_number(V) if not m.divides(self.__congruence_number): # We should never get here - raise ValueError, "BUG in modular degree or congruence number computation of: %s" % self + raise ValueError("BUG in modular degree or congruence number computation of: %s" % self) return self.__congruence_number # Case 2: M > 1 @@ -3525,7 +3525,7 @@ def cremona_label(self, space=False): try: X = self.database_curve() except RuntimeError: - raise RuntimeError, "Cremona label not known for %s."%self + raise RuntimeError("Cremona label not known for %s."%self) self.__cremona_label = X.__cremona_label return self.cremona_label(space) @@ -3572,13 +3572,13 @@ def reduction(self,p): """ p = rings.Integer(p) if not p.is_prime(): - raise AttributeError, "p must be prime." + raise AttributeError("p must be prime.") disc = self.discriminant() if not disc.valuation(p) == 0: local_data=self.local_data(p) if local_data.has_good_reduction(): return local_data.minimal_model().change_ring(rings.GF(p)) - raise AttributeError, "The curve must have good reduction at p." + raise AttributeError("The curve must have good reduction at p.") return self.change_ring(rings.GF(p)) def torsion_order(self): @@ -3847,7 +3847,7 @@ def cm_discriminant(self): try: return CMJ[self.j_invariant()] except KeyError: - raise ValueError, "%s does not have CM"%self + raise ValueError("%s does not have CM"%self) def quadratic_twist(self, D): @@ -4265,9 +4265,9 @@ def is_isogenous(self, other, proof=True, maxp=200): False """ if not is_EllipticCurve(other): - raise ValueError, "Second argument is not an Elliptic Curve." + raise ValueError("Second argument is not an Elliptic Curve.") if not other.base_field() is QQ: - raise ValueError, "If first argument is an elliptic curve over QQ then the second argument must be also." + raise ValueError("If first argument is an elliptic curve over QQ then the second argument must be also.") if self.is_isomorphic(other): return True @@ -4554,7 +4554,7 @@ def manin_constant(self): from sage.databases.cremona import CremonaDatabase if self.conductor() > CremonaDatabase().largest_conductor(): - raise NotImplementedError, "The Manin constant can only be evaluated for curves in Cremona's tables. If you have not done so, you may wish to install the optional large database." + raise NotImplementedError("The Manin constant can only be evaluated for curves in Cremona's tables. If you have not done so, you may wish to install the optional large database.") E = self.minimal_model() C = self.optimal_curve() @@ -4875,7 +4875,7 @@ def is_good(self, p, check=True): """ if check: if not arith.is_prime(p): - raise ValueError, "p must be prime" + raise ValueError("p must be prime") return self.conductor() % p != 0 @@ -5266,7 +5266,7 @@ def antilogarithm(self, z, max_denominator=None): try: return self(xy) except TypeError: - raise ValueError, "approximated point not on the curve" + raise ValueError("approximated point not on the curve") def integral_x_coords_in_interval(self,xmin,xmax): r""" @@ -5413,7 +5413,7 @@ def integral_points(self, mw_base='auto', both_signs=False, verbose=False): ##################################################################### # INPUT CHECK ####################################################### if not self.is_integral(): - raise ValueError, "integral_points() can only be called on an integral model" + raise ValueError("integral_points() can only be called on an integral model") if mw_base=='auto': mw_base = self.gens() @@ -5422,9 +5422,9 @@ def integral_points(self, mw_base='auto', both_signs=False, verbose=False): try: r = len(mw_base) except TypeError: - raise TypeError, 'mw_base must be a list' + raise TypeError('mw_base must be a list') if not all([P.curve() is self for P in mw_base]): - raise ValueError, "points are not on the correct curve" + raise ValueError("points are not on the correct curve") tors_points = self.torsion_points() @@ -5603,7 +5603,7 @@ def point_preprocessing(free,tor): c1_LLL = tmp if c1_LLL < 0: - raise RuntimeError, 'Unexpected intermediate result. Please try another Mordell-Weil base' + raise RuntimeError('Unexpected intermediate result. Please try another Mordell-Weil base') d_L_0 = R(b1_norm**2 / c1_LLL) @@ -5832,21 +5832,21 @@ def S_integral_points(self, S, mw_base='auto', both_signs=False, verbose=False, if not self.is_integral(): - raise ValueError, "S_integral_points() can only be called on an integral model" + raise ValueError("S_integral_points() can only be called on an integral model") if not all([self.is_p_minimal(s) for s in S]): - raise ValueError, "%s must be p-minimal for all primes in S"%self + raise ValueError("%s must be p-minimal for all primes in S"%self) try: len_S = len(S) if len_S == 0: return self.integral_points(mw_base, both_signs, verbose) if not all([s.is_prime() for s in S]): - raise ValueError, "All elements of S must be prime" + raise ValueError("All elements of S must be prime") S.sort() except TypeError: - raise TypeError, 'S must be a list of primes' + raise TypeError('S must be a list of primes') except AttributeError:#catches: .sort(), .is_prime() - raise AttributeError,'S must be a list of primes' + raise AttributeError('S must be a list of primes') if mw_base=='auto': if verbose: @@ -5859,9 +5859,9 @@ def S_integral_points(self, S, mw_base='auto', both_signs=False, verbose=False, try: r = len(mw_base) except TypeError: - raise TypeError, 'mw_base must be a list' + raise TypeError('mw_base must be a list') if not all([P.curve() is self for P in mw_base]): - raise ValueError, "mw_base-points are not on the correct curve" + raise ValueError("mw_base-points are not on the correct curve") #End Input-Check ###################################################### @@ -5893,7 +5893,7 @@ def reduction_at(p): if tmp > c1_LLL: c1_LLL = tmp if c1_LLL < 0: - raise RuntimeError, 'Unexpected intermediate result. Please try another Mordell-Weil base' + raise RuntimeError('Unexpected intermediate result. Please try another Mordell-Weil base') d_L_0 = R(b1_norm**2 / c1_LLL) #Reducing of upper bound @@ -6237,7 +6237,7 @@ def S_integral_x_coords_with_abs_bounded_by(abs_bound): if tmp > c1_LLL: c1_LLL = tmp if c1_LLL < 0: - raise RuntimeError, 'Unexpected intermediate result. Please try another Mordell-Weil base' + raise RuntimeError('Unexpected intermediate result. Please try another Mordell-Weil base') d_L_0 = R(b1_norm**2 / c1_LLL) #Reducing of upper bound diff --git a/src/sage/schemes/elliptic_curves/ell_tate_curve.py b/src/sage/schemes/elliptic_curves/ell_tate_curve.py index 25274c14cbc..f9516fbd942 100644 --- a/src/sage/schemes/elliptic_curves/ell_tate_curve.py +++ b/src/sage/schemes/elliptic_curves/ell_tate_curve.py @@ -96,9 +96,9 @@ def __init__(self,E,p): 2-adic Tate curve associated to the Elliptic Curve defined by y^2 + x*y + y = x^3 - 33*x + 68 over Rational Field """ if not p.is_prime(): - raise ValueError, "p (=%s) must be a prime"%p + raise ValueError("p (=%s) must be a prime"%p) if E.j_invariant().valuation(p) >= 0: - raise ValueError, "The elliptic curve must have multiplicative reduction at %s"%p + raise ValueError("The elliptic curve must have multiplicative reduction at %s"%p) self._p = ZZ(p) self._E = E self._q = self.parameter() @@ -382,7 +382,7 @@ def L_invariant(self,prec=20): """ if not self.is_split(): - raise RuntimeError, "The curve must have split multiplicative reduction" + raise RuntimeError("The curve must have split multiplicative reduction") qE = self.parameter(prec=prec) n = qE.valuation() u = qE/self._p**n # the p-adic logarithm of Iwasawa normalised by log(p) = 0 @@ -412,7 +412,7 @@ def _isomorphism(self,prec=20): """ if not self.is_split(): - raise RuntimeError, "The curve must have split multiplicative reduction" + raise RuntimeError("The curve must have split multiplicative reduction") Csq = self._Csquare(prec=prec+4) C = Csq.sqrt() @@ -445,7 +445,7 @@ def _inverse_isomorphism(self,prec=20): 1 + 5 + 4*5^3 + 2*5^4 + O(5^5), 5 + 2*5^2 + 3*5^4 + O(5^5)] """ if not self.is_split(): - raise RuntimeError, "The curve must have split multiplicative reduction" + raise RuntimeError("The curve must have split multiplicative reduction") vec = self._isomorphism(prec=prec) return [1/vec[0],-vec[1]/vec[0]**2,-vec[2]/vec[0],(vec[1]*vec[2]-vec[3])/vec[0]**3] @@ -480,13 +480,13 @@ def lift(self,P, prec = 20): p = self._p R = Qp(self._p,prec) if not self._E == P.curve(): - raise ValueError , "The point must lie on the original curve." + raise ValueError("The point must lie on the original curve.") if not self.is_split(): - raise ValueError, "The curve must have split multiplicative reduction." + raise ValueError("The curve must have split multiplicative reduction.") if P.is_zero(): return R(1) if P[0].valuation(p) >= 0: - raise ValueError , "The point must lie in the formal group." + raise ValueError("The point must lie in the formal group.") Eq = self.curve(prec=prec) isom = self._isomorphism(prec=prec) @@ -499,7 +499,7 @@ def lift(self,P, prec = 20): try: Pq = Eq([xx,yy]) except Exception: - raise RuntimeError, "Bug : Point %s does not lie on the curve "%[xx,yy] + raise RuntimeError("Bug : Point %s does not lie on the curve "%[xx,yy]) tt = -xx/yy eqhat = Eq.formal() @@ -541,7 +541,7 @@ def parametrisation_onto_original_curve(self,u,prec=20): (0 : 1 + O(5^20) : 0) """ if not self.is_split(): - raise ValueError, "The curve must have split multiplicative reduction." + raise ValueError("The curve must have split multiplicative reduction.") P = self.parametrisation_onto_tate_curve(u,prec=20) isom = self._inverse_isomorphism(prec=prec) C = isom[0] @@ -589,7 +589,7 @@ def padic_height(self,prec=20): """ if not self.is_split(): - raise NotImplementedError, "The curve must have split multiplicative reduction" + raise NotImplementedError("The curve must have split multiplicative reduction") p = self._p @@ -650,7 +650,7 @@ def padic_regulator(self,prec=20): return K(1) if not self.is_split(): - raise NotImplementedError, "The p-adic regulator is not implemented for non-split multiplicative reduction." + raise NotImplementedError("The p-adic regulator is not implemented for non-split multiplicative reduction.") basis = self._E.gens() diff --git a/src/sage/schemes/elliptic_curves/formal_group.py b/src/sage/schemes/elliptic_curves/formal_group.py index 5d09b2302ef..cd1ddc1a9a4 100644 --- a/src/sage/schemes/elliptic_curves/formal_group.py +++ b/src/sage/schemes/elliptic_curves/formal_group.py @@ -530,7 +530,7 @@ def group_law(self, prec=10): """ prec = max(prec,0) if prec <= 0: - raise ValueError, "The precision must be positive." + raise ValueError("The precision must be positive.") R = rings.PowerSeriesRing(self.curve().base_ring(), 2, 't1,t2') t1, t2 = R.gens() diff --git a/src/sage/schemes/elliptic_curves/gal_reps_number_field.py b/src/sage/schemes/elliptic_curves/gal_reps_number_field.py index d89641cd1d0..79ae9488777 100644 --- a/src/sage/schemes/elliptic_curves/gal_reps_number_field.py +++ b/src/sage/schemes/elliptic_curves/gal_reps_number_field.py @@ -642,7 +642,7 @@ def _semistable_reducible_primes(E): # We suspect that E has CM, so we check: f = K.structure()[0] if f(E.j_invariant()) in cm_j_invariants(f.codomain()): - raise ValueError, "The curve E should not have CM." + raise ValueError("The curve E should not have CM.") L = list(bad_primes) L.sort() @@ -782,7 +782,7 @@ def _possible_normalizers(E, SA): if patience == 0: # We suspect E has CM, so we check: if E.j_invariant() in cm_j_invariants(K): - raise ValueError, "The curve E should not have CM." + raise ValueError("The curve E should not have CM.") else: for p in tr.prime_factors(): diff --git a/src/sage/schemes/elliptic_curves/isogeny_class.py b/src/sage/schemes/elliptic_curves/isogeny_class.py index 5b259be713b..5850fd811e4 100644 --- a/src/sage/schemes/elliptic_curves/isogeny_class.py +++ b/src/sage/schemes/elliptic_curves/isogeny_class.py @@ -658,7 +658,7 @@ def _compute(self): self._mat[i,j] = l self._maps[i][j]=phi else: - raise ValueError, "unknown algorithm '%s'"%algorithm + raise ValueError("unknown algorithm '%s'"%algorithm) def _compute_matrix(self): """ diff --git a/src/sage/schemes/elliptic_curves/isogeny_small_degree.py b/src/sage/schemes/elliptic_curves/isogeny_small_degree.py index 8f027161d11..f4dd5dd084f 100644 --- a/src/sage/schemes/elliptic_curves/isogeny_small_degree.py +++ b/src/sage/schemes/elliptic_curves/isogeny_small_degree.py @@ -1668,7 +1668,7 @@ def isogenies_prime_degree_genus_plus_0_j0(E, l): raise ValueError("%s must be one of %s."%(l,hyperelliptic_primes)) F = E.base_field() if E.j_invariant() != 0: - raise ValueError,("j-invariant must be 0.") + raise ValueError(("j-invariant must be 0.")) if F.characteristic() in [2,3,l]: raise NotImplementedError("Not implemented in characteristic 2, 3 or l.") diff --git a/src/sage/schemes/elliptic_curves/kodaira_symbol.py b/src/sage/schemes/elliptic_curves/kodaira_symbol.py index eec3f2c5ca8..9f0086cf916 100644 --- a/src/sage/schemes/elliptic_curves/kodaira_symbol.py +++ b/src/sage/schemes/elliptic_curves/kodaira_symbol.py @@ -99,7 +99,7 @@ def __init__(self, symbol): n = Integer(symbol) self._n = None if n == 0: - raise ValueError, "Kodaira Symbol code number must be nonzero." + raise ValueError("Kodaira Symbol code number must be nonzero.") if n == 1: self._n = 0 self._roman = 1 @@ -150,7 +150,7 @@ def __init__(self, symbol): self._pari = n return elif len(symbol) == 0: - raise TypeError, "symbol must be a nonempty string" + raise TypeError("symbol must be a nonempty string") if symbol[0] == "I": symbol = symbol[1:] starred = False @@ -203,7 +203,7 @@ def __init__(self, symbol): self._str = "I" + symbol self._latex = "I_{%s}"%(symbol) else: - raise ValueError, "input is not a Kodaira symbol" + raise ValueError("input is not a Kodaira symbol") def __repr__(self): r""" diff --git a/src/sage/schemes/elliptic_curves/modular_parametrization.py b/src/sage/schemes/elliptic_curves/modular_parametrization.py index f7705928335..91833f8f65a 100644 --- a/src/sage/schemes/elliptic_curves/modular_parametrization.py +++ b/src/sage/schemes/elliptic_curves/modular_parametrization.py @@ -208,7 +208,7 @@ def map_to_complex_numbers(self, z, prec=None): raise NotImplementedError z = CC(z) if z.imag() <= 0: - raise ValueError, "Point must be in the upper half plane" + raise ValueError("Point must be in the upper half plane") # TODO: for very small imaginary part, maybe try to transform under # \Gamma_0(N) to a better representative? q = (2*CC.gen()*CC.pi()*z).exp() @@ -274,7 +274,7 @@ def power_series(self, prec=20): """ R = LaurentSeriesRing(RationalField(),'q') if not self._E.is_minimal(): - raise NotImplementedError, "Only implemented for minimal curves." + raise NotImplementedError("Only implemented for minimal curves.") from sage.libs.all import pari old_prec = pari.get_series_precision() pari.set_series_precision(prec-1) diff --git a/src/sage/schemes/elliptic_curves/padic_lseries.py b/src/sage/schemes/elliptic_curves/padic_lseries.py index c9641895f79..1020775cb84 100644 --- a/src/sage/schemes/elliptic_curves/padic_lseries.py +++ b/src/sage/schemes/elliptic_curves/padic_lseries.py @@ -184,9 +184,9 @@ def __init__(self, E, p, use_eclib=True, normalize='L_ratio'): self._normalize = normalize self._use_eclib = use_eclib if not self._p.is_prime(): - raise ValueError, "p (=%s) must be a prime"%p + raise ValueError("p (=%s) must be a prime"%p) if E.conductor() % (self._p)**2 == 0: - raise NotImplementedError, "p (=%s) must be a prime of semi-stable reduction"%p + raise NotImplementedError("p (=%s) must be a prime of semi-stable reduction"%p) try : crla = E.label() @@ -337,7 +337,7 @@ def modular_symbol(self, r, sign=+1, quadratic_twist= +1): else : D = quadratic_twist if sign == -1: - raise NotImplementedError, "Quadratic twists for negative modular symbols are not yet implemented." + raise NotImplementedError("Quadratic twists for negative modular symbols are not yet implemented.") if D > 0: m = self._modular_symbol s = +1 @@ -416,9 +416,9 @@ def measure(self, a, n, prec, quadratic_twist=+1, sign = +1): """ s = ZZ(sign) if s not in [1, -1]: - raise ValueError, "Sign must be +- 1" + raise ValueError("Sign must be +- 1") if quadratic_twist != 1 and s != 1: - raise NotImplementedError, "Quadratic twists not implemented for sign -1" + raise NotImplementedError("Quadratic twists not implemented for sign -1") if quadratic_twist < 0: s = -1 @@ -516,7 +516,7 @@ def alpha(self, prec=20): if a.valuation() < 1: self._alpha[prec] = K(a) return K(a) - raise ValueError, "bug in p-adic L-function alpha" + raise ValueError("bug in p-adic L-function alpha") else: # supersingular case f = f.change_ring(Qp(p, prec, print_mode='series')) a = f.root_field('alpha', check_irreducible=False).gen() @@ -578,14 +578,14 @@ def order_of_vanishing(self): raise NotImplementedError E = self.elliptic_curve() if not E.is_good(self.prime()): - raise ValueError, "prime must be of good reduction" + raise ValueError("prime must be of good reduction") r = E.rank() n = 1 while True: f = self.series(n) v = f.valuation() if v < n and v < r: - raise RuntimeError, "while computing p-adic order of vanishing, got a contradiction: the curve is %s, the curve has rank %s, but the p-adic L-series vanishes to order <= %s"%(E, r, v) + raise RuntimeError("while computing p-adic order of vanishing, got a contradiction: the curve is %s, the curve has rank %s, but the p-adic L-series vanishes to order <= %s"%(E, r, v)) if v == r: self.__ord = v return v @@ -855,26 +855,26 @@ def series(self, n=2, quadratic_twist=+1, prec=5, eta=0): """ n = ZZ(n) if n < 1: - raise ValueError, "n (=%s) must be a positive integer"%n + raise ValueError("n (=%s) must be a positive integer"%n) eta = ZZ(eta) % (self._p - 1) # check if the conditions on quadratic_twist are satisfied D = ZZ(quadratic_twist) if D != 1: - if eta != 0: raise NotImplementedError, "quadratic twists only implemented for the 0th Teichmueller component" + if eta != 0: raise NotImplementedError("quadratic twists only implemented for the 0th Teichmueller component") if D % 4 == 0: d = D//4 if not d.is_squarefree() or d % 4 == 1: - raise ValueError, "quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D + raise ValueError("quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D) else: if not D.is_squarefree() or D % 4 != 1: - raise ValueError, "quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D + raise ValueError("quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D) if gcd(D,self._p) != 1: - raise ValueError, "quadratic twist (=%s) must be coprime to p (=%s) "%(D,self._p) + raise ValueError("quadratic twist (=%s) must be coprime to p (=%s) "%(D,self._p)) if gcd(D,self._E.conductor())!= 1: for ell in prime_divisors(D): if valuation(self._E.conductor(),ell) > valuation(D,ell) : - raise ValueError, "can not twist a curve of conductor (=%s) by the quadratic twist (=%s)."%(self._E.conductor(),D) + raise ValueError("can not twist a curve of conductor (=%s) by the quadratic twist (=%s)."%(self._E.conductor(),D)) p = self._p @@ -1075,23 +1075,23 @@ def series(self, n=3, quadratic_twist = +1, prec=5, eta = 0): """ n = ZZ(n) if n < 1: - raise ValueError, "n (=%s) must be a positive integer"%n + raise ValueError("n (=%s) must be a positive integer"%n) # check if the conditions on quadratic_twist are satisfied D = ZZ(quadratic_twist) if D != 1: - if eta != 0: raise NotImplementedError, "quadratic twists only implemented for the 0th Teichmueller component" + if eta != 0: raise NotImplementedError("quadratic twists only implemented for the 0th Teichmueller component") if D % 4 == 0: d = D//4 if not d.is_squarefree() or d % 4 == 1: - raise ValueError, "quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D + raise ValueError("quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D) else: if not D.is_squarefree() or D % 4 != 1: - raise ValueError, "quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D + raise ValueError("quadratic_twist (=%s) must be a fundamental discriminant of a quadratic field"%D) if gcd(D,self._E.conductor())!= 1: for ell in prime_divisors(D): if valuation(self._E.conductor(),ell) > valuation(D,ell) : - raise ValueError, "can not twist a curve of conductor (=%s) by the quadratic twist (=%s)."%(self._E.conductor(),D) + raise ValueError("can not twist a curve of conductor (=%s) by the quadratic twist (=%s)."%(self._E.conductor(),D)) p = self._p if p == 2 and self._normalize : @@ -1280,7 +1280,7 @@ def frobenius(self, prec=20, algorithm = "mw"): E = self._E p = self._p if algorithm != "mw" and algorithm !="approx": - raise ValueError, "Unknown algorithm %s."%algorithm + raise ValueError("Unknown algorithm %s."%algorithm) if algorithm == "approx": return self.__phi_bpr(prec=prec) if p < 4 and algorithm == "mw": @@ -1298,7 +1298,7 @@ def frobenius(self, prec=20, algorithm = "mw"): # return a vector for PARI's ellchangecurve to pass from e1 to e2 def isom(e1,e2): if not e1.is_isomorphic(e2): - raise ValueError, "Curves must be isomorphic." + raise ValueError("Curves must be isomorphic.") usq = (e1.discriminant()/e2.discriminant()).nth_root(6) u = usq.sqrt() s = (u * e2.a1() - e1.a1() )/ZZ(2) @@ -1394,7 +1394,7 @@ def __phi_bpr(self, prec=0): gamma = gamma % p**dga verbose("gamma_prec increased to %s\n gamma is now %s"%(dga,gamma)) else: - raise RuntimeError, "Bug: no delta or gamma can exist" + raise RuntimeError("Bug: no delta or gamma can exist") # end of approximation of delta and gamma R = Qp(p,max(dpr,dga)+1) diff --git a/src/sage/schemes/elliptic_curves/padics.py b/src/sage/schemes/elliptic_curves/padics.py index 2c52eba6e74..09c44a4b8d1 100644 --- a/src/sage/schemes/elliptic_curves/padics.py +++ b/src/sage/schemes/elliptic_curves/padics.py @@ -58,11 +58,11 @@ def __check_padic_hypotheses(self, p): """ p = rings.Integer(p) if not p.is_prime(): - raise ValueError, "p = (%s) must be prime"%p + raise ValueError("p = (%s) must be prime"%p) if p == 2: - raise ValueError, "p must be odd" + raise ValueError("p must be odd") if self.conductor() % p == 0 or self.ap(p) % p == 0: - raise ArithmeticError, "p must be a good ordinary prime" + raise ArithmeticError("p must be a good ordinary prime") return p @@ -252,11 +252,11 @@ def padic_regulator(self, p, prec=20, height=None, check_hypotheses=True): p = Integer(p) # this is assumed in code below if check_hypotheses: if not p.is_prime(): - raise ValueError, "p = (%s) must be prime"%p + raise ValueError("p = (%s) must be prime"%p) if p == 2: - raise ValueError, "p must be odd" # todo + raise ValueError("p must be odd") # todo if self.conductor() % (p**2) == 0: - raise ArithmeticError, "p must be a semi-stable prime" + raise ArithmeticError("p must be a semi-stable prime") if self.conductor() % p == 0: Eq = self.tate_curve(p) @@ -645,15 +645,15 @@ def padic_height(self, p, prec=20, sigma=None, check_hypotheses=True): """ if check_hypotheses: if not p.is_prime(): - raise ValueError, "p = (%s) must be prime"%p + raise ValueError("p = (%s) must be prime"%p) if p == 2: - raise ValueError, "p must be odd" # todo + raise ValueError("p must be odd") # todo if self.conductor() % (p**2) == 0: - raise ArithmeticError, "p must be a semi-stable prime" + raise ArithmeticError("p must be a semi-stable prime") prec = int(prec) if prec < 1: - raise ValueError, "prec (=%s) must be at least 1" % prec + raise ValueError("prec (=%s) must be at least 1" % prec) if self.conductor() % p == 0: Eq = self.tate_curve(p,prec=prec) @@ -801,17 +801,17 @@ def padic_height_via_multiply(self, p, prec=20, E2=None, check_hypotheses=True): """ if check_hypotheses: if not p.is_prime(): - raise ValueError, "p = (%s) must be prime"%p + raise ValueError("p = (%s) must be prime"%p) if p == 2: - raise ValueError, "p must be odd" # todo + raise ValueError("p must be odd") # todo if self.conductor() % p == 0: - raise ArithmeticError, "must have good reduction at p" + raise ArithmeticError("must have good reduction at p") if self.ap(p) % p == 0: - raise ArithmeticError, "must be ordinary at p" + raise ArithmeticError("must be ordinary at p") prec = int(prec) if prec < 1: - raise ValueError, "prec (=%s) must be at least 1" % prec + raise ValueError("prec (=%s) must be at least 1" % prec) # For notation and definitions, see ``Computing p-adic heights via point # multiplication'' (David Harvey, still in draft form) @@ -992,13 +992,13 @@ def padic_sigma(self, p, N=20, E2=None, check=False, check_hypotheses=True): # the precision loss estimates (below) very carefully; I think it # may become necessary to compute E2 to an even higher precision. if p < 5: - raise NotImplementedError, "p (=%s) must be at least 5" % p + raise NotImplementedError("p (=%s) must be at least 5" % p) N = int(N) if N <= 2: # a few special cases for small N if N < 1: - raise ValueError, "N (=%s) must be at least 1" % prec + raise ValueError("N (=%s) must be at least 1" % prec) if N == 1: # return simply t + O(t^2) @@ -1013,12 +1013,12 @@ def padic_sigma(self, p, N=20, E2=None, check=False, check_hypotheses=True): K(self.a1()/2, 1)], prec=3) if self.discriminant().valuation(p) != 0: - raise NotImplementedError, "equation of curve must be minimal at p" + raise NotImplementedError("equation of curve must be minimal at p") if E2 is None: E2 = self.padic_E2(p, N-2, check_hypotheses=False) elif E2.precision_absolute() < N-2: - raise ValueError, "supplied E2 has insufficient precision" + raise ValueError("supplied E2 has insufficient precision") QQt = LaurentSeriesRing(RationalField(), "x") @@ -1181,17 +1181,17 @@ def padic_sigma_truncated(self, p, N=20, lamb=0, E2=None, check_hypotheses=True) # the precision loss estimates (below) very carefully; I think it # may become necessary to compute E2 to an even higher precision. if p < 5: - raise NotImplementedError, "p (=%s) must be at least 5" % p + raise NotImplementedError("p (=%s) must be at least 5" % p) N = int(N) lamb = int(lamb) if lamb < 0: - raise ValueError, "lamb (=%s) must be at least 0" % lamb + raise ValueError("lamb (=%s) must be at least 0" % lamb) # a few special cases for small N if N <= 1: - raise ValueError, "N (=%s) must be at least 2" % N + raise ValueError("N (=%s) must be at least 2" % N) if N == 2: # return t + a_1/2 t^2 + O(t^3) @@ -1200,12 +1200,12 @@ def padic_sigma_truncated(self, p, N=20, lamb=0, E2=None, check_hypotheses=True) K(self.a1()/2, lamb+1)], prec=3) if self.discriminant().valuation(p) != 0: - raise NotImplementedError, "equation of curve must be minimal at p" + raise NotImplementedError("equation of curve must be minimal at p") if E2 is None: E2 = self.padic_E2(p, N-2, check_hypotheses=False) elif E2.precision_absolute() < N-2: - raise ValueError, "supplied E2 has insufficient precision" + raise ValueError("supplied E2 has insufficient precision") # The main part of the algorithm is exactly the same as # for padic_sigma(), but we truncate all the series earlier. @@ -1508,10 +1508,10 @@ def matrix_of_frobenius(self, p, prec=20, check=False, check_hypotheses=True, al if algorithm == "auto": algorithm = "standard" if p < 6*prec else "sqrtp" elif algorithm == "sqrtp" and p < 6*prec: - raise ValueError, "sqrtp algorithm is only available when p > 6*prec" + raise ValueError("sqrtp algorithm is only available when p > 6*prec") if algorithm not in ["standard", "sqrtp"]: - raise ValueError, "unknown algorithm '%s'" % algorithm + raise ValueError("unknown algorithm '%s'" % algorithm) # todo: maybe it would be good if default prec was None, and then # it selects an appropriate precision based on how large the prime @@ -1519,11 +1519,11 @@ def matrix_of_frobenius(self, p, prec=20, check=False, check_hypotheses=True, al # todo: implement the p == 3 case if p < 5: - raise NotImplementedError, "p (=%s) must be at least 5" % p + raise NotImplementedError("p (=%s) must be at least 5" % p) prec = int(prec) if prec < 1: - raise ValueError, "prec (=%s) must be at least 1" % prec + raise ValueError("prec (=%s) must be at least 1" % prec) # To run matrix_of_frobenius(), we need to have the equation in the # form y^2 = x^3 + ax + b, whose discriminant is invertible mod p. diff --git a/src/sage/schemes/elliptic_curves/period_lattice.py b/src/sage/schemes/elliptic_curves/period_lattice.py index 511b8258960..227b32f6ff8 100644 --- a/src/sage/schemes/elliptic_curves/period_lattice.py +++ b/src/sage/schemes/elliptic_curves/period_lattice.py @@ -539,7 +539,7 @@ def _compute_periods_real(self, prec=None, algorithm='sage'): return (R(periods[0]), C(periods[1])) if algorithm!='sage': - raise ValueError, "invalid value of 'algorithm' parameter" + raise ValueError("invalid value of 'algorithm' parameter") pi = R.pi() # Up to now everything has been exact in AA or QQbar, but now @@ -693,7 +693,7 @@ def is_rectangular(self): """ if self.is_real(): return self.real_flag == +1 - raise RuntimeError, "Not defined for non-real lattices." + raise RuntimeError("Not defined for non-real lattices.") def real_period(self, prec = None, algorithm='sage'): """ @@ -731,7 +731,7 @@ def real_period(self, prec = None, algorithm='sage'): """ if self.is_real(): return self.basis(prec,algorithm)[0] - raise RuntimeError, "Not defined for non-real lattices." + raise RuntimeError("Not defined for non-real lattices.") def omega(self, prec = None): r""" @@ -939,7 +939,7 @@ def sigma(self, z, prec = None, flag=0): try: return self.E.pari_curve(prec).ellsigma(z, flag) except AttributeError: - raise NotImplementedError, "sigma function not yet implemented for period lattices of curves not defined over Q." + raise NotImplementedError("sigma function not yet implemented for period lattices of curves not defined over Q.") def curve(self): r""" @@ -1052,7 +1052,7 @@ def coordinates(self, z, rounding=None): C = ComplexField() z = C(z) except TypeError: - raise TypeError, "%s is not a complex number"%z + raise TypeError("%s is not a complex number"%z) prec = C.precision() from sage.matrix.all import Matrix from sage.modules.all import vector @@ -1119,7 +1119,7 @@ def reduce(self, z): z = C(z) z_is_real = z.is_real() except TypeError: - raise TypeError, "%s is not a complex number"%z + raise TypeError("%s is not a complex number"%z) prec = C.precision() if self.real_flag: w1,w2 = self.basis(prec) # w1 real @@ -1323,7 +1323,7 @@ def elliptic_logarithm(self, P, prec=None, reduce=True): 1.17058357737548897849026170185581196033579563441850967539191867385734983296504066660506637438866628981886518901958717288150400849746892393771983141354014895386251320571643977497740116710952913769943240797618468987304985625823413440999754037939123032233879499904283600304184828809773650066658885672885 - 1.13513899565966043682474529757126359416758251309237866586896869548539516543734207347695898664875799307727928332953834601460994992792519799260968053875387282656993476491590607092182964878750169490985439873220720963653658829712494879003124071110818175013453207439440032582917366703476398880865439217473*I """ if not P.curve() is self.E: - raise ValueError, "Point is on the wrong curve" + raise ValueError("Point is on the wrong curve") if prec is None: prec = RealField().precision() if P.is_zero(): @@ -1621,7 +1621,7 @@ def elliptic_exponential(self, z, to_curve=True): z = C(z) z_is_real = z.is_real() except TypeError: - raise TypeError, "%s is not a complex number"%z + raise TypeError("%s is not a complex number"%z) prec = C.precision() # test for the point at infinity: @@ -1792,7 +1792,7 @@ def extended_agm_iteration(a,b,c): """ if not isinstance(a, (RealNumber,ComplexNumber)): - raise ValueError, "values must be real or complex numbers" + raise ValueError("values must be real or complex numbers") eps = a.parent().one().real()>>(a.parent().precision()-10) while True: a1 = (a + b)/2 diff --git a/src/sage/schemes/elliptic_curves/weierstrass_morphism.py b/src/sage/schemes/elliptic_curves/weierstrass_morphism.py index bd48bf77a48..f703ddc9141 100644 --- a/src/sage/schemes/elliptic_curves/weierstrass_morphism.py +++ b/src/sage/schemes/elliptic_curves/weierstrass_morphism.py @@ -71,7 +71,7 @@ def __init__(self, u=1, r=0, s=0, t=0): (u, r, s, t) """ if u==0: - raise ValueError, "u!=0 required for baseWI" + raise ValueError("u!=0 required for baseWI") self.u=u; self.r=r; self.s=s; self.t=t def __cmp__(self, other): @@ -235,7 +235,7 @@ def __call__(self, EorP): x-=r*z y-=(s*x+t*z) return [x/u**2,y/u**3,z] - raise ValueError, "baseWI(a) only for a=(x,y), (x:y:z) or (a1,a2,a3,a4,a6)" + raise ValueError("baseWI(a) only for a=(x,y), (x:y:z) or (a1,a2,a3,a4,a6)") def isomorphisms(E,F,JustOne=False): r""" @@ -272,7 +272,7 @@ def isomorphisms(E,F,JustOne=False): """ from ell_generic import is_EllipticCurve if not is_EllipticCurve(E) or not is_EllipticCurve(F): - raise ValueError, "arguments are not elliptic curves" + raise ValueError("arguments are not elliptic curves") K = E.base_ring() # if not K == F.base_ring(): return [] j=E.j_invariant() @@ -422,15 +422,15 @@ def __init__(self, E=None, urst=None, F=None): if E!=None: if not is_EllipticCurve(E): - raise ValueError, "First argument must be an elliptic curve or None" + raise ValueError("First argument must be an elliptic curve or None") if F!=None: if not is_EllipticCurve(F): - raise ValueError, "Third argument must be an elliptic curve or None" + raise ValueError("Third argument must be an elliptic curve or None") if urst!=None: if len(urst)!=4: - raise ValueError, "Second argument must be [u,r,s,t] or None" + raise ValueError("Second argument must be [u,r,s,t] or None") if len([par for par in [E,urst,F] if par!=None])<2: - raise ValueError, "At most 1 argument can be None" + raise ValueError("At most 1 argument can be None") if F==None: # easy case baseWI.__init__(self,*urst) @@ -452,7 +452,7 @@ def __init__(self, E=None, urst=None, F=None): if urst==None: # try to construct the morphism urst=isomorphisms(E,F,True) if urst==None: - raise ValueError, "Elliptic curves not isomorphic." + raise ValueError("Elliptic curves not isomorphic.") baseWI.__init__(self, *urst) Morphism.__init__(self, Hom(E(0).parent(), F(0).parent())) self._domain_curve = E @@ -463,7 +463,7 @@ def __init__(self, E=None, urst=None, F=None): # none of the parameters is None: baseWI.__init__(self,*urst) if F!=EllipticCurve(baseWI.__call__(self,list(E.a_invariants()))): - raise ValueError, "second argument is not an isomorphism from first argument to third argument" + raise ValueError("second argument is not an isomorphism from first argument to third argument") else: Morphism.__init__(self, Hom(E(0).parent(), F(0).parent())) self._domain_curve = E @@ -585,7 +585,7 @@ def __mul__(self,other): w=baseWI.__mul__(self,other) return WeierstrassIsomorphism(other._domain_curve, w.tuple(), self._codomain_curve) else: - raise ValueError, "Domain of first argument must equal codomain of second" + raise ValueError("Domain of first argument must equal codomain of second") def __repr__(self): r""" diff --git a/src/sage/schemes/generic/algebraic_scheme.py b/src/sage/schemes/generic/algebraic_scheme.py index f88a45d65ca..d98ec00c814 100644 --- a/src/sage/schemes/generic/algebraic_scheme.py +++ b/src/sage/schemes/generic/algebraic_scheme.py @@ -234,7 +234,7 @@ def __init__(self, A): Category of schemes over Integer Ring """ if not ambient_space.is_AmbientSpace(A): - raise TypeError, "A (=%s) must be an ambient space" + raise TypeError("A (=%s) must be an ambient space") self.__A = A self.__divisor_group = {} scheme.Scheme.__init__(self, A.base_scheme()) @@ -444,7 +444,7 @@ def embedding_morphism(self): if '_embedding_morphism' in self.__dict__: hom = self._embedding_morphism if isinstance(hom, tuple): - raise(hom[0], hom[1]) + raise hom[0] return hom ambient = self.ambient_space() return self.hom(ambient.coordinate_ring().gens(), ambient) @@ -490,7 +490,7 @@ def embedding_center(self): """ if '_embedding_center' in self.__dict__: return self._embedding_center - raise AttributeError, 'This algebraic scheme does not have a designated point.' + raise AttributeError('This algebraic scheme does not have a designated point.') def ngens(self): """ @@ -637,11 +637,11 @@ def __init__(self, X, Y): self.__X = X self.__Y = Y if not isinstance(X, AlgebraicScheme_subscheme): - raise TypeError, "X must be a closed subscheme of an ambient space." + raise TypeError("X must be a closed subscheme of an ambient space.") if not isinstance(Y, AlgebraicScheme_subscheme): - raise TypeError, "Y must be a closed subscheme of an ambient space." + raise TypeError("Y must be a closed subscheme of an ambient space.") if X.ambient_space() != Y.ambient_space(): - raise ValueError, "X and Y must be embedded in the same ambient space." + raise ValueError("X and Y must be embedded in the same ambient space.") # _latex_ and _repr_ assume all of the above conditions and should be # probably changed if they are relaxed! A = X.ambient_space() @@ -813,11 +813,11 @@ def _check_satisfies_equations(self, v): coords = list(v) for f in self.__X.defining_polynomials(): if f(coords) != 0: - raise TypeError, "Coordinates %s do not define a point on %s"%(v,self) + raise TypeError("Coordinates %s do not define a point on %s"%(v,self)) for f in self.__Y.defining_polynomials(): if f(coords) != 0: return True - raise TypeError, "Coordinates %s do not define a point on %s"%(v,self) + raise TypeError("Coordinates %s do not define a point on %s"%(v,self)) def rational_points(self, F=None, bound=0): """ @@ -849,9 +849,9 @@ def rational_points(self, F=None, bound=0): if bound == 0: if is_RationalField(F): - raise TypeError, "A positive bound (= %s) must be specified."%bound + raise TypeError("A positive bound (= %s) must be specified."%bound) if not is_FiniteField(F): - raise TypeError, "Argument F (= %s) must be a finite field."%F + raise TypeError("Argument F (= %s) must be a finite field."%F) pts = [] for P in self.ambient_space().rational_points(F): try: @@ -964,11 +964,11 @@ def _check_satisfies_equations(self, v): for f in self.defining_polynomials(): if f(coords) != 0: # it must be "!=0" instead of "if f(v)", e.g., # because of p-adic base rings. - raise TypeError, "Coordinates %s do not define a point on %s"%(coords,self) + raise TypeError("Coordinates %s do not define a point on %s"%(coords,self)) try: return self.ambient_space()._check_satisfies_equations(coords) except TypeError: - raise TypeError, "Coordinates %s do not define a point on %s"%(coords,self) + raise TypeError("Coordinates %s do not define a point on %s"%(coords,self)) def base_extend(self, R): """ @@ -1357,10 +1357,10 @@ def union(self, other): True """ if not isinstance(other, AlgebraicScheme_subscheme): - raise TypeError, "other (=%s) must be a closed algebraic subscheme of an ambient space"%other + raise TypeError("other (=%s) must be a closed algebraic subscheme of an ambient space"%other) A = self.ambient_space() if other.ambient_space() != A: - raise ValueError, "other (=%s) must be in the same ambient space as self"%other + raise ValueError("other (=%s) must be in the same ambient space as self"%other) return A.subscheme(self.defining_ideal().intersection(other.defining_ideal())) __add__ = union @@ -1381,10 +1381,10 @@ def intersection(self, other): y """ if not isinstance(other, AlgebraicScheme_subscheme): - raise TypeError, "other (=%s) must be a closed algebraic subscheme of an ambient space"%other + raise TypeError("other (=%s) must be a closed algebraic subscheme of an ambient space"%other) A = self.ambient_space() if other.ambient_space() != A: - raise ValueError, "other (=%s) must be in the same ambient space as self"%other + raise ValueError("other (=%s) must be in the same ambient space as self"%other) return A.subscheme(self.defining_ideal() + other.defining_ideal()) def complement(self, other=None): @@ -1436,10 +1436,9 @@ def complement(self, other=None): if other == A: other = A.subscheme([]) else: - raise TypeError, \ - "Argument other (=%s) must be a closed algebraic subscheme of an ambient space"%other + raise TypeError("Argument other (=%s) must be a closed algebraic subscheme of an ambient space"%other) if other.ambient_space() != A: - raise ValueError, "other (=%s) must be in the same ambient space as self"%other + raise ValueError("other (=%s) must be in the same ambient space as self"%other) return AlgebraicScheme_quasi(other, self) def rational_points(self, F=None, bound=0): @@ -1488,15 +1487,15 @@ def rational_points(self, F=None, bound=0): X = self(F) if is_RationalField(F) or F == ZZ: if not bound > 0: - raise TypeError, "A positive bound (= %s) must be specified."%bound + raise TypeError("A positive bound (= %s) must be specified."%bound) try: return X.points(bound) except TypeError: - raise TypeError, "Unable to enumerate points over %s."%F + raise TypeError("Unable to enumerate points over %s."%F) try: return X.points() except TypeError: - raise TypeError, "Unable to enumerate points over %s."%F + raise TypeError("Unable to enumerate points over %s."%F) def change_ring(self,R): r""" @@ -1652,8 +1651,7 @@ def projective_embedding(self, i=None, X=None): else: i = int(i) if i < 0 or i > n: - raise ValueError, \ - "Argument i (=%s) must be between 0 and %s, inclusive"%(i, n) + raise ValueError("Argument i (=%s) must be between 0 and %s, inclusive"%(i, n)) try: return self.__projective_embedding[i] except AttributeError: @@ -1881,7 +1879,7 @@ def affine_patch(self, i): PP = self.ambient_space() n = PP.dimension() if i < 0 or i > n: - raise ValueError, "Argument i (= %s) must be between 0 and %s."%(i, n) + raise ValueError("Argument i (= %s) must be between 0 and %s."%(i, n)) try: return self.__affine_patches[i] except AttributeError: diff --git a/src/sage/schemes/generic/ambient_space.py b/src/sage/schemes/generic/ambient_space.py index be68b74485d..72cfdaa000d 100644 --- a/src/sage/schemes/generic/ambient_space.py +++ b/src/sage/schemes/generic/ambient_space.py @@ -52,10 +52,10 @@ def __init__(self, n, R=ZZ): sage: TestSuite(A).run() # not tested (abstract scheme with no elements?) """ if not is_CommutativeRing(R): - raise TypeError, "R (=%s) must be a commutative ring"%R + raise TypeError("R (=%s) must be a commutative ring"%R) n = Integer(n) if n < 0: - raise ValueError, "n (=%s) must be nonnegative"%n + raise ValueError("n (=%s) must be nonnegative"%n) self._dimension_relative = n Scheme.__init__(self, R) @@ -376,7 +376,7 @@ def dimension_absolute(self): base = self.base_scheme() if base.is_noetherian(): return self.dimension_relative() + base.dimension() - raise NotImplementedError, "Cannot compute the dimension of this scheme." + raise NotImplementedError("Cannot compute the dimension of this scheme.") dimension = dimension_absolute diff --git a/src/sage/schemes/generic/divisor.py b/src/sage/schemes/generic/divisor.py index cb92a54102a..b75404ccf68 100644 --- a/src/sage/schemes/generic/divisor.py +++ b/src/sage/schemes/generic/divisor.py @@ -305,21 +305,18 @@ def __init__(self, v, parent=None, check=True, reduce=True): try: C = t[1].scheme() except (TypeError, AttributeError): - raise TypeError, \ - "Argument v (= %s) must consist of multiplicities and points on a scheme." + raise TypeError("Argument v (= %s) must consist of multiplicities and points on a scheme.") else: try: C = t.scheme() except TypeError: - raise TypeError, \ - "Argument v (= %s) must consist of multiplicities and points on a scheme." + raise TypeError("Argument v (= %s) must consist of multiplicities and points on a scheme.") parent = DivisorGroup(C) else: - raise TypeError, \ - "Argument v (= %s) must consist of multiplicities and points on a scheme." + raise TypeError("Argument v (= %s) must consist of multiplicities and points on a scheme.") else: if not isinstance(parent, DivisorGroup_curve): - raise TypeError, "parent (of type %s) must be a DivisorGroup_curve"%type(parent) + raise TypeError("parent (of type %s) must be a DivisorGroup_curve"%type(parent)) C = parent.scheme() if len(v) < 1: diff --git a/src/sage/schemes/generic/glue.py b/src/sage/schemes/generic/glue.py index e2a4f222117..7ca742222b1 100644 --- a/src/sage/schemes/generic/glue.py +++ b/src/sage/schemes/generic/glue.py @@ -33,11 +33,11 @@ class GluedScheme(scheme.Scheme): def __init__(self, f, g, check=True): if check: if not morphism.is_SchemeMorphism(f): - raise TypeError, "f (=%s) must be a scheme morphism"%f + raise TypeError("f (=%s) must be a scheme morphism"%f) if not morphism.is_SchemeMorphism(g): - raise TypeError, "g (=%s) must be a scheme morphism"%g + raise TypeError("g (=%s) must be a scheme morphism"%g) if f.domain() != g.domain(): - raise ValueError, "f (=%s) and g (=%s) must have the same domain"%(f,g) + raise ValueError("f (=%s) and g (=%s) must have the same domain"%(f,g)) self.__f = f self.__g = g diff --git a/src/sage/schemes/generic/homset.py b/src/sage/schemes/generic/homset.py index c224832eb3c..d855bac3589 100644 --- a/src/sage/schemes/generic/homset.py +++ b/src/sage/schemes/generic/homset.py @@ -396,7 +396,7 @@ def _element_constructor_(self, x, check=True): if is_RingHomomorphism(x): return SchemeMorphism_spec(self, x, check=check) - raise TypeError, "x must be a ring homomorphism, list or tuple" + raise TypeError("x must be a ring homomorphism, list or tuple") #******************************************************************* diff --git a/src/sage/schemes/generic/hypersurface.py b/src/sage/schemes/generic/hypersurface.py index 3fd84d58e58..f38453152b4 100644 --- a/src/sage/schemes/generic/hypersurface.py +++ b/src/sage/schemes/generic/hypersurface.py @@ -92,10 +92,9 @@ def __init__(self, poly, ambient=None): True """ if not is_MPolynomial(poly): - raise TypeError, \ - "Defining polynomial (=%s) must be a multivariate polynomial."%poly + raise TypeError("Defining polynomial (=%s) must be a multivariate polynomial."%poly) if not poly.is_homogeneous(): - raise TypeError, "Defining polynomial (=%s) must be homogeneous."%poly + raise TypeError("Defining polynomial (=%s) must be homogeneous."%poly) if ambient == None: R = poly.parent() from sage.schemes.projective.projective_space import ProjectiveSpace @@ -178,7 +177,7 @@ def __init__(self, poly, ambient=None): True """ if not is_MPolynomial(poly): - raise TypeError, "Defining polynomial (= %s) must be a multivariate polynomial"%poly + raise TypeError("Defining polynomial (= %s) must be a multivariate polynomial"%poly) if ambient == None: R = poly.parent() from sage.schemes.affine.affine_space import AffineSpace diff --git a/src/sage/schemes/generic/morphism.py b/src/sage/schemes/generic/morphism.py index 09c6bc32652..96c5a0b996a 100644 --- a/src/sage/schemes/generic/morphism.py +++ b/src/sage/schemes/generic/morphism.py @@ -150,7 +150,7 @@ def __init__(self, parent): """ if not isinstance(parent, Homset): - raise TypeError, "parent (=%s) must be a Homspace"%parent + raise TypeError("parent (=%s) must be a Homspace"%parent) Element.__init__(self, parent) self._domain = parent.domain() self._codomain = parent.codomain() @@ -340,7 +340,7 @@ def __pow__(self, n, dummy=None): 'SchemeMorphism_id' and 'SchemeMorphism_id' """ if not self.is_endomorphism(): - raise TypeError, "self must be an endomorphism." + raise TypeError("self must be an endomorphism.") if n==0: return self.domain().identity_morphism() return generic_power(self, n) @@ -489,7 +489,7 @@ def __init__(self, parent): """ SchemeMorphism.__init__(self, parent) if self.domain().base_scheme() != self.codomain(): - raise ValueError, "parent must have codomain equal the base scheme of domain." + raise ValueError("parent must have codomain equal the base scheme of domain.") def _repr_defn(self): r""" @@ -598,7 +598,7 @@ def __call__(self, P): NotImplementedError """ if not is_SchemeTopologicalPoint(P) and P in self.domain(): - raise TypeError, "P (=%s) must be a topological scheme point of %s"%(P, self) + raise TypeError("P (=%s) must be a topological scheme point of %s"%(P, self)) S = self.ring_homomorphism().inverse_image(P.prime_ideal()) return self.codomain()(S) @@ -733,15 +733,15 @@ def __init__(self, parent, polys, check=True): """ if check: if not isinstance(polys, (list, tuple)): - raise TypeError, "polys (=%s) must be a list or tuple"%polys + raise TypeError("polys (=%s) must be a list or tuple"%polys) source_ring = parent.domain().coordinate_ring() target = parent.codomain().ambient_space() if len(polys) != target.ngens(): - raise ValueError, "there must be %s polynomials"%target.ngens() + raise ValueError("there must be %s polynomials"%target.ngens()) try: polys = [source_ring(poly) for poly in polys] except TypeError: - raise TypeError, "polys (=%s) must be elements of %s"%(polys,source_ring) + raise TypeError("polys (=%s) must be elements of %s"%(polys,source_ring)) if isinstance(source_ring, QuotientRing_generic): lift_polys = [f.lift() for f in polys] else: @@ -852,7 +852,7 @@ def __call__(self, x,check=True): if not isinstance(x,SchemeMorphism_point): x = self.domain()(x) elif x.codomain()!=self.domain(): - raise TypeError, "Point must be in the domain of the function" + raise TypeError("Point must be in the domain of the function") P = [f(x._coords) for f in self.defining_polynomials()] return self.codomain().point(P,check) diff --git a/src/sage/schemes/generic/point.py b/src/sage/schemes/generic/point.py index 28c6142a2bd..ad9c4d87c50 100644 --- a/src/sage/schemes/generic/point.py +++ b/src/sage/schemes/generic/point.py @@ -152,7 +152,7 @@ def __init__(self, S, P, check=False): # unfortunately is_prime() is only implemented in a small # number of cases if check and not P.is_prime(): - raise ValueError, "The argument %s must be a prime ideal of %s"%(P, R) + raise ValueError("The argument %s must be a prime ideal of %s"%(P, R)) SchemeTopologicalPoint.__init__(self, S) self.__P = P diff --git a/src/sage/schemes/generic/scheme.py b/src/sage/schemes/generic/scheme.py index 100026c16ed..751f1d7be04 100644 --- a/src/sage/schemes/generic/scheme.py +++ b/src/sage/schemes/generic/scheme.py @@ -544,7 +544,7 @@ def coordinate_ring(self): try: return self._coordinate_ring except AttributeError: - raise ValueError, "This scheme has no associated coordinated ring (defined)." + raise ValueError("This scheme has no associated coordinated ring (defined).") def dimension_absolute(self): """ @@ -642,7 +642,7 @@ def hom(self, x, Y=None, check=True): if is_Scheme(x): return self.Hom(x).natural_map() else: - raise TypeError, "unable to determine codomain" + raise TypeError("unable to determine codomain") return self.Hom(Y)(x, check) def _Hom_(self, Y, category=None, check=True): @@ -718,10 +718,10 @@ def count_points(self, n): """ F = self.base_ring() if not F.is_finite(): - raise TypeError, "Point counting only defined for schemes over finite fields" + raise TypeError("Point counting only defined for schemes over finite fields") q = F.cardinality() if not q.is_prime(): - raise NotImplementedError, "Point counting only implemented for schemes over prime fields" + raise NotImplementedError("Point counting only implemented for schemes over prime fields") a = [] for i in range(1, n+1): F1 = GF(q**i, name='z') diff --git a/src/sage/schemes/generic/spec.py b/src/sage/schemes/generic/spec.py index e31c698dc1e..d7f8f9faab6 100644 --- a/src/sage/schemes/generic/spec.py +++ b/src/sage/schemes/generic/spec.py @@ -115,15 +115,15 @@ def __init__(self, R, S=None): Spectrum of Integer Ring """ if not is_CommutativeRing(R): - raise TypeError, "R (=%s) must be a commutative ring"%R + raise TypeError("R (=%s) must be a commutative ring"%R) self.__R = R if not S is None: if not is_CommutativeRing(S): - raise TypeError, "S (=%s) must be a commutative ring"%S + raise TypeError("S (=%s) must be a commutative ring"%S) try: S.hom(R) except TypeError: - raise ValueError, "There must be a natural map S --> R, but S = %s and R = %s"%(S,R) + raise ValueError("There must be a natural map S --> R, but S = %s and R = %s"%(S,R)) AffineScheme.__init__(self, S) def _cmp_(self, X): diff --git a/src/sage/schemes/hyperelliptic_curves/constructor.py b/src/sage/schemes/hyperelliptic_curves/constructor.py index 91cfb87dace..69678d4201d 100644 --- a/src/sage/schemes/hyperelliptic_curves/constructor.py +++ b/src/sage/schemes/hyperelliptic_curves/constructor.py @@ -192,17 +192,16 @@ def HyperellipticCurve(f, h=0, names=None, PP=None, check_squarefree=True): if P(2) == 0: # characteristic 2 if h == 0: - raise ValueError, \ - "In characteristic 2, argument h (= %s) must be non-zero."%h + raise ValueError("In characteristic 2, argument h (= %s) must be non-zero."%h) if h[g+1] == 0 and f[2*g+1]**2 == f[2*g+2]*h[g]**2: - raise ValueError, "Not a hyperelliptic curve: " \ - "highly singular at infinity." + raise ValueError("Not a hyperelliptic curve: " \ + "highly singular at infinity.") should_be_coprime = [h, f*h.derivative()**2+f.derivative()**2] else: # characteristic not 2 if not F.degree() in [2*g+1, 2*g+2]: - raise ValueError, "Not a hyperelliptic curve: " \ - "highly singular at infinity." + raise ValueError("Not a hyperelliptic curve: " \ + "highly singular at infinity.") should_be_coprime = [F, F.derivative()] try: smooth = should_be_coprime[0].gcd(should_be_coprime[1]).degree()==0 @@ -210,13 +209,13 @@ def HyperellipticCurve(f, h=0, names=None, PP=None, check_squarefree=True): try: smooth = should_be_coprime[0].resultant(should_be_coprime[1])!=0 except (AttributeError, NotImplementedError, TypeError): - raise NotImplementedError, "Cannot determine whether " \ + raise NotImplementedError("Cannot determine whether " \ "polynomials %s have a common root. Use " \ "check_squarefree=False to skip this check." % \ - should_be_coprime + should_be_coprime) if not smooth: - raise ValueError, "Not a hyperelliptic curve: " \ - "singularity in the provided affine patch." + raise ValueError("Not a hyperelliptic curve: " \ + "singularity in the provided affine patch.") R = P.base_ring() PP = ProjectiveSpace(2, R) if names is None: diff --git a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_finite_field.py b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_finite_field.py index e9f29ed6056..0d29160d8cb 100644 --- a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_finite_field.py +++ b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_finite_field.py @@ -100,7 +100,7 @@ def _frobenius_matrix(self, N=None): f, h = self.hyperelliptic_polynomials() if h != 0: # need y^2 = f(x) - raise NotImplementedError, "only implemented for curves y^2 = f(x)" + raise NotImplementedError("only implemented for curves y^2 = f(x)") sign = 1 if not f.is_monic(): @@ -534,7 +534,7 @@ def _Cartier_matrix_cached(self): #checks if p == 2: - raise ValueError, "p must be odd"; + raise ValueError("p must be odd"); g = self.genus() @@ -543,17 +543,17 @@ def _Cartier_matrix_cached(self): f,h = self.hyperelliptic_polynomials() #This implementation only deals with h=0 if h!=0: - raise ValueError, "E must be of the form y^2 = f(x)" + raise ValueError("E must be of the form y^2 = f(x)") d = f.degree() #this implementation is for odd degree only, even degree will be handled later. if d%2 == 0: - raise ValueError, "In this implementation the degree of f must be odd" + raise ValueError("In this implementation the degree of f must be odd") #Compute resultant to make sure no repeated roots df=f.derivative() R=df.resultant(f) if R == 0: - raise ValueError, "curve is not smooth" + raise ValueError("curve is not smooth") #computing F, since the entries of the matrix are c_i where F= \sum c_i x^i diff --git a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_g2_generic.py b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_g2_generic.py index cda6e7f3e1b..208c823dd99 100644 --- a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_g2_generic.py +++ b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_g2_generic.py @@ -40,8 +40,7 @@ def kummer_morphism(self): except AttributeError: pass if not self.is_odd_degree(): - raise TypeError, \ - "Kummer embedding not determined for even degree model curves." + raise TypeError("Kummer embedding not determined for even degree model curves.") J = self.jacobian() K = J.kummer_surface() return self._kummer_morphism diff --git a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_generic.py b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_generic.py index 8da8b78f341..fc7af1412bd 100644 --- a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_generic.py +++ b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_generic.py @@ -217,7 +217,7 @@ def lift_x(self, x, all=False): if all: return [] else: - raise ValueError, "No point with x-coordinate %s on %s"%(x, self) + raise ValueError("No point with x-coordinate %s on %s"%(x, self)) def genus(self): @@ -284,14 +284,14 @@ def odd_degree_model(self): """ f, h = self._hyperelliptic_polynomials if h: - raise NotImplementedError, "odd_degree_model only implemented for curves in Weierstrass form" + raise NotImplementedError("odd_degree_model only implemented for curves in Weierstrass form") if f.degree() % 2: # already odd, so just yield self return self rts = f.roots(multiplicities=False) if not rts: - raise ValueError, "No odd degree model exists over field of definition" + raise ValueError("No odd degree model exists over field of definition") rt = rts[0] x = f.parent().gen() fnew = f((x*rt + 1)/x).numerator() # move rt to "infinity" @@ -403,7 +403,7 @@ def local_coordinates_at_nonweierstrass(self, P, prec=20, name='t'): """ d = P[1] if d == 0: - raise TypeError, "P = %s is a Weierstrass point. Use local_coordinates_at_weierstrass instead!"%P + raise TypeError("P = %s is a Weierstrass point. Use local_coordinates_at_weierstrass instead!"%P) pol = self.hyperelliptic_polynomials()[0] L = PowerSeriesRing(self.base_ring(), name) t = L.gen() @@ -457,7 +457,7 @@ def local_coordinates_at_weierstrass(self, P, prec=20, name='t'): - Francis Clarke (2012-08-26) """ if P[1] != 0: - raise TypeError, "P = %s is not a finite Weierstrass point. Use local_coordinates_at_nonweierstrass instead!"%P + raise TypeError("P = %s is not a finite Weierstrass point. Use local_coordinates_at_nonweierstrass instead!"%P) L = PowerSeriesRing(self.base_ring(), name) t = L.gen() pol = self.hyperelliptic_polynomials()[0] diff --git a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py index 3d61f0bfd0a..1619f72cf7d 100644 --- a/src/sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py +++ b/src/sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py @@ -97,7 +97,7 @@ def local_analytic_interpolation(self, P, Q): """ prec = self.base_ring().precision_cap() if self.is_same_disc(P,Q) == False: - raise ValueError, "%s and %s are not in the same residue disc"%(P,Q) + raise ValueError("%s and %s are not in the same residue disc"%(P,Q)) disc = self.residue_disc(P) t = PowerSeriesRing(self.base_ring(), 't', prec).gen(0) if disc == self.change_ring(self.base_ring().residue_field())(0,1,0): @@ -235,7 +235,7 @@ def find_char_zero_weier_point(self, Q): - Jennifer Balakrishnan """ if self.is_in_weierstrass_disc(Q) == False: - raise ValueError, "%s is not in a Weierstrass disc"%Q + raise ValueError("%s is not in a Weierstrass disc"%Q) points = self.weierstrass_points() for P in points: if self.is_same_disc(P,Q): @@ -844,7 +844,7 @@ def coleman_integral(self, w, P, Q, algorithm = 'None'): elif w._coeff(x,-y)*x.derivative()/(-2*y)+w._coeff(x,y)*x.derivative()/(2*y) == 0: return self.coleman_integral(w,self(Q[0],-Q[1]), self(Q[0],Q[1]), algorithm)/2 else: - raise ValueError, "The differential is not odd: use coleman_integral_from_weierstrass_via_boundary" + raise ValueError("The differential is not odd: use coleman_integral_from_weierstrass_via_boundary") elif self.is_weierstrass(Q): if f == 0: @@ -852,7 +852,7 @@ def coleman_integral(self, w, P, Q, algorithm = 'None'): elif w._coeff(x,-y)*x.derivative()/(-2*y)+w._coeff(x,y)*x.derivative()/(2*y) == 0: return -self.coleman_integral(w,self(P[0],-P[1]), self(P[0],P[1]), algorithm)/2 else: - raise ValueError, "The differential is not odd: use coleman_integral_from_weierstrass_via_boundary" + raise ValueError("The differential is not odd: use coleman_integral_from_weierstrass_via_boundary") else: return f(Q[0], Q[1]) - f(P[0], P[1]) + sum([vec[i] * basis_values[i] for i in range(dim)]) # this is just a dot product... @@ -909,7 +909,7 @@ def frobenius(self, P=None): f, f2 = self.hyperelliptic_polynomials() if f2 != 0: - raise NotImplementedError, "Curve must be in weierstrass normal form." + raise NotImplementedError("Curve must be in weierstrass normal form.") h = (f(x**p) - f**p) def _frob(P): diff --git a/src/sage/schemes/hyperelliptic_curves/invariants.py b/src/sage/schemes/hyperelliptic_curves/invariants.py index f7a5da7341b..17ff90b9791 100644 --- a/src/sage/schemes/hyperelliptic_curves/invariants.py +++ b/src/sage/schemes/hyperelliptic_curves/invariants.py @@ -245,7 +245,7 @@ def clebsch_invariants(f): """ R = f.parent().base_ring() if R.characteristic() in [2, 3, 5]: - raise NotImplementedError, "Invariants of binary sextics/genus 2 hyperelliptic curves not implemented in characteristics 2, 3, and 5" + raise NotImplementedError("Invariants of binary sextics/genus 2 hyperelliptic curves not implemented in characteristics 2, 3, and 5") U = ubs(f) L = U['A'], U['B'], U['C'], U['D'] diff --git a/src/sage/schemes/hyperelliptic_curves/jacobian_generic.py b/src/sage/schemes/hyperelliptic_curves/jacobian_generic.py index 17541921459..23c3ccddc28 100644 --- a/src/sage/schemes/hyperelliptic_curves/jacobian_generic.py +++ b/src/sage/schemes/hyperelliptic_curves/jacobian_generic.py @@ -127,7 +127,7 @@ def point(self, mumford, check=True): try: return self(self.base_ring())(mumford) except AttributeError: - raise ValueError, "Arguments must determine a valid Mumford divisor." + raise ValueError("Arguments must determine a valid Mumford divisor.") def _point_homset(self, *args, **kwds): return jacobian_homset.JacobianHomset_divisor_classes(*args, **kwds) diff --git a/src/sage/schemes/hyperelliptic_curves/jacobian_homset.py b/src/sage/schemes/hyperelliptic_curves/jacobian_homset.py index 2be13fdbc95..5272a3cf599 100644 --- a/src/sage/schemes/hyperelliptic_curves/jacobian_homset.py +++ b/src/sage/schemes/hyperelliptic_curves/jacobian_homset.py @@ -145,14 +145,14 @@ def __call__(self, P): return JacobianMorphism_divisor_class_field(self, tuple(P)) if is_SchemeMorphism(P1) and is_SchemeMorphism(P2): return self(P1) - self(P2) - raise TypeError, "Argument P (= %s) must have length 2."%P + raise TypeError("Argument P (= %s) must have length 2."%P) elif isinstance(P,JacobianMorphism_divisor_class_field) and self == P.parent(): return P elif is_SchemeMorphism(P): x0 = P[0]; y0 = P[1] R, x = PolynomialRing(self.value_ring(), 'x').objgen() return self((x-x0,R(y0))) - raise TypeError, "Argument P (= %s) does not determine a divisor class"%P + raise TypeError("Argument P (= %s) does not determine a divisor class"%P) def _cmp_(self,other): if self.curve() == other.curve(): @@ -174,9 +174,9 @@ def value_ring(self): if is_Spec(T): return T.coordinate_ring() else: - raise TypeError, "Domain of argument must be of the form Spec(S)." + raise TypeError("Domain of argument must be of the form Spec(S).") def base_extend(self, R): if R != ZZ: - raise NotImplementedError, "Jacobian point sets viewed as modules over rings other than ZZ not implemented" + raise NotImplementedError("Jacobian point sets viewed as modules over rings other than ZZ not implemented") return self diff --git a/src/sage/schemes/hyperelliptic_curves/jacobian_morphism.py b/src/sage/schemes/hyperelliptic_curves/jacobian_morphism.py index 237e5975d67..e2d20ad00f6 100644 --- a/src/sage/schemes/hyperelliptic_curves/jacobian_morphism.py +++ b/src/sage/schemes/hyperelliptic_curves/jacobian_morphism.py @@ -381,9 +381,8 @@ def __init__(self, parent, polys, check=True): f, h = C.hyperelliptic_polynomials() a, b = polys if not (b**2 + h*b - f)%a == 0: - raise ValueError, \ - "Argument polys (= %s) must be divisor on curve %s."%( - polys, C) + raise ValueError("Argument polys (= %s) must be divisor on curve %s."%( + polys, C)) genus = C.genus() if a.degree() > genus: polys = cantor_reduction(a, b, f, h, genus) diff --git a/src/sage/schemes/jacobians/abstract_jacobian.py b/src/sage/schemes/jacobians/abstract_jacobian.py index f883d374fd2..6393003edb5 100644 --- a/src/sage/schemes/jacobians/abstract_jacobian.py +++ b/src/sage/schemes/jacobians/abstract_jacobian.py @@ -102,11 +102,11 @@ def __init__(self, C): TypeError: C (=Projective Curve over Ring of integers modulo 6 defined by x + y + z) must be defined over a field. """ if not is_Scheme(C): - raise TypeError, "Argument (=%s) must be a scheme."%C + raise TypeError("Argument (=%s) must be a scheme."%C) if C.base_ring() not in _Fields: - raise TypeError, "C (=%s) must be defined over a field."%C + raise TypeError("C (=%s) must be defined over a field."%C) if C.dimension() != 1: - raise ValueError, "C (=%s) must have dimension 1."%C + raise ValueError("C (=%s) must have dimension 1."%C) self.__curve = C Scheme.__init__(self, C.base_scheme()) diff --git a/src/sage/schemes/plane_conics/con_field.py b/src/sage/schemes/plane_conics/con_field.py index 00a6c3c89d3..6f0540b7ce9 100644 --- a/src/sage/schemes/plane_conics/con_field.py +++ b/src/sage/schemes/plane_conics/con_field.py @@ -117,8 +117,8 @@ def base_extend(self, S): if B == S: return self if not S.has_coerce_map_from(B): - raise ValueError, "No natural map from the base ring of self " \ - "(= %s) to S (= %s)" % (self, S) + raise ValueError("No natural map from the base ring of self " \ + "(= %s) to S (= %s)" % (self, S)) from constructor import Conic con = Conic([S(c) for c in self.coefficients()], \ self.variable_names()) @@ -494,10 +494,10 @@ def has_rational_point(self, point = False, except (TypeError, NameError): pass - raise NotImplementedError, "No correct conversion implemented for converting the Magma point %s on %s to a correct Sage point on self (=%s)" % (M_pt, M, self) + raise NotImplementedError("No correct conversion implemented for converting the Magma point %s on %s to a correct Sage point on self (=%s)" % (M_pt, M, self)) if algorithm != 'default': - raise ValueError, "Unknown algorithm: %s" % algorithm + raise ValueError("Unknown algorithm: %s" % algorithm) if is_ComplexField(B): if point: @@ -525,8 +525,8 @@ def has_rational_point(self, point = False, if point: return ret return ret[0] - raise NotImplementedError, "has_rational_point not implemented for " \ - "conics over base field %s" % B + raise NotImplementedError("has_rational_point not implemented for " \ + "conics over base field %s" % B) def has_singular_point(self, point = False): r""" @@ -588,7 +588,7 @@ def has_singular_point(self, point = False): return True, self.point([1,0,(a/f).sqrt()]) if (d/f).is_square(): return True, self.point([0,1,(d/f).sqrt()]) - raise NotImplementedError, "Sorry, find singular point on conics not implemented over all fields of characteristic 2." + raise NotImplementedError("Sorry, find singular point on conics not implemented over all fields of characteristic 2.") pt = [e, c, b] if self.defining_polynomial()(pt) == 0: return True, self.point(pt) @@ -653,9 +653,9 @@ def hom(self, x, Y=None): q = Y.defining_polynomial()/im.defining_polynomial() if not (q.numerator().is_constant() and q.denominator().is_constant()): - raise ValueError, "The matrix x (= %s) does not define a " \ + raise ValueError("The matrix x (= %s) does not define a " \ "map from self (= %s) to Y (= %s)" % \ - (x, self, Y) + (x, self, Y)) x = Sequence(x*vector(self.ambient_space().gens())) return self.Hom(Y)(x, check = False) return ProjectiveCurve_generic.hom(self, x, Y) @@ -834,7 +834,7 @@ def parametrization(self, point=None, morphism=True): par = self._parametrization else: if not self.is_smooth(): - raise ValueError, "The conic self (=%s) is not smooth, hence does not have a parametrization." % self + raise ValueError("The conic self (=%s) is not smooth, hence does not have a parametrization." % self) if point == None: point = self.rational_point() point = Sequence(point) @@ -929,8 +929,8 @@ def random_rational_point(self, *args1, **args2): """ if not self.is_smooth(): - raise NotImplementedError, "Sorry, random points not implemented " \ - "for non-smooth conics" + raise NotImplementedError("Sorry, random points not implemented " \ + "for non-smooth conics") par = self.parametrization() x = 0 y = 0 @@ -1046,8 +1046,8 @@ def rational_point(self, algorithm = 'default', read_cache = True): read_cache = read_cache) if bl: return pt - raise ValueError, "Conic %s has no rational points over %s!" % \ - (self, self.ambient_space().base_ring()) + raise ValueError("Conic %s has no rational points over %s!" % \ + (self, self.ambient_space().base_ring())) def singular_point(self): @@ -1072,8 +1072,8 @@ def singular_point(self): """ b = self.has_singular_point(point = True) if not b[0]: - raise ValueError, "The conic self (= %s) has no rational " \ - "singular point" % self + raise ValueError("The conic self (= %s) has no rational " \ + "singular point" % self) return b[1] def symmetric_matrix(self): @@ -1099,9 +1099,9 @@ def symmetric_matrix(self): if self.base_ring().characteristic() == 2: if b == 0 and c == 0 and e == 0: return matrix([[a,0,0],[0,d,0],[0,0,f]]) - raise ValueError, "The conic self (= %s) has no symmetric matrix " \ + raise ValueError("The conic self (= %s) has no symmetric matrix " \ "because the base field has characteristic 2" % \ - self + self) from sage.matrix.constructor import matrix return matrix([[ a , b/2, c/2 ], [ b/2, d , e/2 ], diff --git a/src/sage/schemes/plane_conics/con_number_field.py b/src/sage/schemes/plane_conics/con_number_field.py index 15a159c6626..4ae48d817f3 100644 --- a/src/sage/schemes/plane_conics/con_number_field.py +++ b/src/sage/schemes/plane_conics/con_number_field.py @@ -230,9 +230,9 @@ def has_rational_point(self, point = False, obstruction = False, algorithm='local', read_cache=False) if ret[0]: - raise RuntimeError, "Outputs of algorithms in " \ + raise RuntimeError("Outputs of algorithms in " \ "has_rational_point disagree " \ - "for conic %s" % self + "for conic %s" % self) return ret if point: return False, None @@ -240,8 +240,8 @@ def has_rational_point(self, point = False, obstruction = False, if algorithm == 'local': if point: - raise ValueError, "Algorithm 'local' cannot be combined " \ - "with point = True in has_rational_point" + raise ValueError("Algorithm 'local' cannot be combined " \ + "with point = True in has_rational_point") obs = self.local_obstructions(infinite = True, finite = False, read_cache = read_cache) if obs != []: @@ -259,9 +259,9 @@ def has_rational_point(self, point = False, obstruction = False, if algorithm == 'rnfisnorm': from sage.modules.free_module_element import vector if obstruction: - raise ValueError, "Algorithm rnfisnorm cannot be combined " \ + raise ValueError("Algorithm rnfisnorm cannot be combined " \ "with obstruction = True in " \ - "has_rational_point" + "has_rational_point") D, T = self.diagonal_matrix() abc = [D[0,0], D[1,1], D[2,2]] for j in range(3): @@ -302,11 +302,11 @@ def has_rational_point(self, point = False, obstruction = False, return False, None return False if algorithm == 'qfsolve': - raise TypeError, "Algorithm qfsolve in has_rational_point only " \ - "for conics over QQ, not over %s" % B + raise TypeError("Algorithm qfsolve in has_rational_point only " \ + "for conics over QQ, not over %s" % B) if obstruction: - raise ValueError, "Invalid combination: obstruction=True and " \ - "algorithm=%s" % algorithm + raise ValueError("Invalid combination: obstruction=True and " \ + "algorithm=%s" % algorithm) return ProjectiveConic_field.has_rational_point(self, point = point, algorithm = algorithm, read_cache = False) diff --git a/src/sage/schemes/plane_conics/con_rational_field.py b/src/sage/schemes/plane_conics/con_rational_field.py index 16ebd6065fc..3125f652ff5 100644 --- a/src/sage/schemes/plane_conics/con_rational_field.py +++ b/src/sage/schemes/plane_conics/con_rational_field.py @@ -232,8 +232,8 @@ def is_locally_solvable(self, p): if p.domain() is QQ and is_RealField(p.codomain()): p = -1 else: - raise TypeError, "p (=%s) needs to be a prime of base field " \ - "B ( =`QQ`) in is_locally_solvable" % p + raise TypeError("p (=%s) needs to be a prime of base field " \ + "B ( =`QQ`) in is_locally_solvable" % p) if hilbert_symbol(a, b, p) == -1: if self._local_obstruction == None: self._local_obstruction = p @@ -363,7 +363,7 @@ def parametrization(self, point=None, morphism=True): par = self._parametrization else: if not self.is_smooth(): - raise ValueError, "The conic self (=%s) is not smooth, hence does not have a parametrization." % self + raise ValueError("The conic self (=%s) is not smooth, hence does not have a parametrization." % self) if point == None: point = self.rational_point() point = Sequence(point) diff --git a/src/sage/schemes/plane_conics/constructor.py b/src/sage/schemes/plane_conics/constructor.py index b7304468f3a..00846c765a4 100644 --- a/src/sage/schemes/plane_conics/constructor.py +++ b/src/sage/schemes/plane_conics/constructor.py @@ -156,7 +156,7 @@ def Conic(base_field, F=None, names=None, unique=True): if isinstance(f, SchemeMorphism_point_affine): C = Sequence(f, universe = base_field) if len(C) != 2: - raise TypeError, "points in F (=%s) must be planar"%F + raise TypeError("points in F (=%s) must be planar"%F) C.append(1) elif isinstance(f, SchemeMorphism_point_projective_field): C = Sequence(f, universe = base_field) @@ -165,20 +165,20 @@ def Conic(base_field, F=None, names=None, unique=True): if len(C) == 2: C.append(1) else: - raise TypeError, "F (=%s) must be a sequence of planar " \ - "points" % F + raise TypeError("F (=%s) must be a sequence of planar " \ + "points" % F) if len(C) != 3: - raise TypeError, "points in F (=%s) must be planar" % F + raise TypeError("points in F (=%s) must be planar" % F) P = C.universe() if not is_IntegralDomain(P): - raise TypeError, "coordinates of points in F (=%s) must " \ - "be in an integral domain" % F + raise TypeError("coordinates of points in F (=%s) must " \ + "be in an integral domain" % F) L.append(Sequence([C[0]**2, C[0]*C[1], C[0]*C[2], C[1]**2, C[1]*C[2], C[2]**2], P.fraction_field())) M=Matrix(L) if unique and M.rank() != 5: - raise ValueError, "points in F (=%s) do not define a unique " \ - "conic" % F + raise ValueError("points in F (=%s) do not define a unique " \ + "conic" % F) con = Conic(base_field, Sequence(M.right_kernel().gen()), names) con.point(F[0]) return con @@ -191,8 +191,8 @@ def Conic(base_field, F=None, names=None, unique=True): if len(F) == 6: return Conic(F[0]*x**2 + F[1]*x*y + F[2]*x*z + F[3]*y**2 + \ F[4]*y*z + F[5]*z**2) - raise TypeError, "F (=%s) must be a sequence of 3 or 6" \ - "coefficients" % F + raise TypeError("F (=%s) must be a sequence of 3 or 6" \ + "coefficients" % F) if is_QuadraticForm(F): F = F.matrix() if is_Matrix(F) and F.is_square() and F.ncols() == 3: @@ -202,16 +202,16 @@ def Conic(base_field, F=None, names=None, unique=True): F = vector(temp_ring.gens()) * F * vector(temp_ring.gens()) if not is_MPolynomial(F): - raise TypeError, "F (=%s) must be a three-variable polynomial or " \ - "a sequence of points or coefficients" % F + raise TypeError("F (=%s) must be a three-variable polynomial or " \ + "a sequence of points or coefficients" % F) if F.total_degree() != 2: - raise TypeError, "F (=%s) must have degree 2" % F + raise TypeError("F (=%s) must have degree 2" % F) if base_field == None: base_field = F.base_ring() if not is_IntegralDomain(base_field): - raise ValueError, "Base field (=%s) must be a field" % base_field + raise ValueError("Base field (=%s) must be a field" % base_field) base_field = base_field.fraction_field() if names == None: names = F.parent().variable_names() @@ -222,11 +222,11 @@ def Conic(base_field, F=None, names=None, unique=True): F = pol_ring(F(x/z,y/z)*z**2) if F == 0: - raise ValueError, "F must be nonzero over base field %s" % base_field + raise ValueError("F must be nonzero over base field %s" % base_field) if F.total_degree() != 2: - raise TypeError, "F (=%s) must have degree 2 over base field %s" % \ - (F, base_field) + raise TypeError("F (=%s) must have degree 2 over base field %s" % \ + (F, base_field)) if F.parent().ngens() == 3: P2 = ProjectiveSpace(2, base_field, names) @@ -240,4 +240,4 @@ def Conic(base_field, F=None, names=None, unique=True): return ProjectiveConic_number_field(P2, F) return ProjectiveConic_field(P2, F) - raise TypeError, "Number of variables of F (=%s) must be 2 or 3" % F + raise TypeError("Number of variables of F (=%s) must be 2 or 3" % F) diff --git a/src/sage/schemes/plane_curves/affine_curve.py b/src/sage/schemes/plane_curves/affine_curve.py index 0c6355eec86..1bba7d56565 100644 --- a/src/sage/schemes/plane_curves/affine_curve.py +++ b/src/sage/schemes/plane_curves/affine_curve.py @@ -40,17 +40,17 @@ def _repr_type(self): def __init__(self, A, X): if not is_AffineSpace(A): - raise TypeError, "A (=%s) must be an affine space"%A + raise TypeError("A (=%s) must be an affine space"%A) Curve_generic.__init__(self, A, X) d = self.dimension() if d != 1: - raise ValueError, "defining equations (=%s) define a scheme of dimension %s != 1"%(X,d) + raise ValueError("defining equations (=%s) define a scheme of dimension %s != 1"%(X,d)) class AffineCurve_generic(Curve_generic): def __init__(self, A, f): P = f.parent() if not (is_AffineSpace(A) and A.dimension != 2): - raise TypeError, "Argument A (= %s) must be an affine plane."%A + raise TypeError("Argument A (= %s) must be an affine plane."%A) Curve_generic.__init__(self, A, [f]) def _repr_type(self): @@ -373,7 +373,7 @@ def rational_points(self, algorithm="enum"): try: X1 = f.Adj_div() except (TypeError, RuntimeError) as s: - raise RuntimeError, str(s) + "\n\n ** Unable to use the Brill-Noether Singular package to compute all points (see above)." + raise RuntimeError(str(s) + "\n\n ** Unable to use the Brill-Noether Singular package to compute all points (see above).") X2 = singular.NSplaces(1, X1) R = X2[5][1][1] @@ -396,8 +396,8 @@ def rational_points(self, algorithm="enum"): S_enum = self.rational_points(algorithm = "enum") S_bn = self.rational_points(algorithm = "bn") if S_enum != S_bn: - raise RuntimeError, "Bug in rational_points -- different algorithms give different answers for curve %s!"%self + raise RuntimeError("Bug in rational_points -- different algorithms give different answers for curve %s!"%self) return S_enum else: - raise ValueError, "No algorithm '%s' known"%algorithm + raise ValueError("No algorithm '%s' known"%algorithm) diff --git a/src/sage/schemes/plane_curves/constructor.py b/src/sage/schemes/plane_curves/constructor.py index 9768c39a09f..82eca03c33e 100644 --- a/src/sage/schemes/plane_curves/constructor.py +++ b/src/sage/schemes/plane_curves/constructor.py @@ -173,7 +173,7 @@ def Curve(F): F = Sequence(F) P = F.universe() if not is_MPolynomialRing(P): - raise TypeError, "universe of F must be a multivariate polynomial ring" + raise TypeError("universe of F must be a multivariate polynomial ring") for f in F: if not f.is_homogeneous(): @@ -186,13 +186,13 @@ def Curve(F): return ProjectiveSpaceCurve_generic(A, F) if not is_MPolynomial(F): - raise TypeError, "F (=%s) must be a multivariate polynomial"%F + raise TypeError("F (=%s) must be a multivariate polynomial"%F) P = F.parent() k = F.base_ring() if F.parent().ngens() == 2: if F == 0: - raise ValueError, "defining polynomial of curve must be nonzero" + raise ValueError("defining polynomial of curve must be nonzero") A2 = AffineSpace(2, P.base_ring()) A2._coordinate_ring = P @@ -206,7 +206,7 @@ def Curve(F): elif F.parent().ngens() == 3: if F == 0: - raise ValueError, "defining polynomial of curve must be nonzero" + raise ValueError("defining polynomial of curve must be nonzero") P2 = ProjectiveSpace(2, P.base_ring()) P2._coordinate_ring = P @@ -224,6 +224,6 @@ def Curve(F): else: - raise TypeError, "Number of variables of F (=%s) must be 2 or 3"%F + raise TypeError("Number of variables of F (=%s) must be 2 or 3"%F) diff --git a/src/sage/schemes/plane_curves/projective_curve.py b/src/sage/schemes/plane_curves/projective_curve.py index 2058ac3ac26..2780cb45da9 100644 --- a/src/sage/schemes/plane_curves/projective_curve.py +++ b/src/sage/schemes/plane_curves/projective_curve.py @@ -36,16 +36,16 @@ def _repr_type(self): def __init__(self, A, X): if not is_ProjectiveSpace(A): - raise TypeError, "A (=%s) must be a projective space"%A + raise TypeError("A (=%s) must be a projective space"%A) Curve_generic_projective.__init__(self, A, X) d = self.dimension() if d != 1: - raise ValueError, "defining equations (=%s) define a scheme of dimension %s != 1"%(X,d) + raise ValueError("defining equations (=%s) define a scheme of dimension %s != 1"%(X,d)) class ProjectiveCurve_generic(Curve_generic_projective): def __init__(self, A, f): if not (is_ProjectiveSpace(A) and A.dimension != 2): - raise TypeError, "Argument A (= %s) must be a projective plane."%A + raise TypeError("Argument A (= %s) must be a projective plane."%A) Curve_generic_projective.__init__(self, A, [f]) def _repr_type(self): @@ -526,9 +526,9 @@ def _points_via_singular(self, sort=True): try: X1 = f.Adj_div() except (TypeError, RuntimeError) as s: - raise RuntimeError, str(s) + "\n\n ** Unable to use the\ + raise RuntimeError(str(s) + "\n\n ** Unable to use the\ Brill-Noether Singular package to\ - compute all points (see above)." + compute all points (see above).") X2 = singular.NSplaces(1, X1) R = X2[5][1][1] @@ -599,7 +599,7 @@ def riemann_roch_basis(self, D): try: X1 = f.Adj_div() except (TypeError, RuntimeError) as s: - raise RuntimeError, str(s) + "\n\n ** Unable to use the Brill-Noether Singular package to compute all points (see above)." + raise RuntimeError(str(s) + "\n\n ** Unable to use the Brill-Noether Singular package to compute all points (see above).") X2 = singular.NSplaces(1, X1) # retrieve list of all computed closed points (possibly of degree >1) v = X2[3].sage_flattened_str_list() # We use sage_flattened_str_list since iterating through @@ -687,14 +687,14 @@ def rational_points(self, algorithm="enum", sort=True): S_enum = self.rational_points(algorithm = "enum") S_bn = self.rational_points(algorithm = "bn") if S_enum != S_bn: - raise RuntimeError, "Bug in rational_points -- different\ + raise RuntimeError("Bug in rational_points -- different\ algorithms give different answers for\ - curve %s!"%self + curve %s!"%self) return S_enum else: - raise ValueError, "No algorithm '%s' known"%algorithm + raise ValueError("No algorithm '%s' known"%algorithm) def Hasse_bounds(q, genus=1): r""" diff --git a/src/sage/schemes/projective/projective_homset.py b/src/sage/schemes/projective/projective_homset.py index 60e42f8c0f0..28f09984970 100644 --- a/src/sage/schemes/projective/projective_homset.py +++ b/src/sage/schemes/projective/projective_homset.py @@ -86,12 +86,12 @@ def points(self, B=0): R = self.value_ring() if is_RationalField(R): if not B > 0: - raise TypeError, "A positive bound B (= %s) must be specified."%B + raise TypeError("A positive bound B (= %s) must be specified."%B) return enum_projective_rational_field(self,B) elif is_FiniteField(R): return enum_projective_finite_field(self.extended_codomain()) else: - raise TypeError, "Unable to enumerate points over %s."%R + raise TypeError("Unable to enumerate points over %s."%R) class SchemeHomset_points_projective_ring(SchemeHomset_points): """ @@ -154,11 +154,11 @@ def points(self, B=0): R = self.value_ring() if R == ZZ: if not B > 0: - raise TypeError, "A positive bound B (= %s) must be specified."%B + raise TypeError("A positive bound B (= %s) must be specified."%B) from sage.schemes.projective.projective_rational_point import enum_projective_rational_field return enum_projective_rational_field(self,B) else: - raise TypeError, "Unable to enumerate points over %s."%R + raise TypeError("Unable to enumerate points over %s."%R) #******************************************************************* diff --git a/src/sage/schemes/projective/projective_point.py b/src/sage/schemes/projective/projective_point.py index b67c37b6882..0f45514276d 100644 --- a/src/sage/schemes/projective/projective_point.py +++ b/src/sage/schemes/projective/projective_point.py @@ -771,7 +771,7 @@ def green_function(self, G,v, **kwds): raise NotImplementedError("error bounds only for dimension 1") err = R(err) if not err>0: - raise ValueError, "Error bound (=%s) must be positive."%err + raise ValueError("Error bound (=%s) must be positive."%err) #if doing error estimates, compute needed number of iterates res = F.resultant() diff --git a/src/sage/schemes/toric/chow_group.py b/src/sage/schemes/toric/chow_group.py index d7568f01440..17e4509d550 100644 --- a/src/sage/schemes/toric/chow_group.py +++ b/src/sage/schemes/toric/chow_group.py @@ -264,7 +264,7 @@ def degree(self): for i, cone in enumerate(self.parent()._cones): if self.lift()[i]!=0: if cone_dim not in [None,cone.dim()]: - raise ValueError, 'Chow cycle is not of definite degree.' + raise ValueError('Chow cycle is not of definite degree.') cone_dim = cone.dim() self._dim = ambient_dim - cone_dim return self._dim @@ -532,7 +532,7 @@ def cohomology_class(self): """ toric_variety = self.parent().scheme() if not toric_variety.is_orbifold(): - raise(ValueError, 'The toric variety may have at most orbifold singularities!') + raise ValueError HH = toric_variety.cohomology_ring() coeff = self.lift() return sum([ HH(cone) * coeff[i] for i,cone in enumerate(self.parent()._cones) ]) @@ -565,10 +565,10 @@ def create_key_and_extra_args(self, toric_variety, base_ring=ZZ, check=True): True """ if not is_ToricVariety(toric_variety): - raise ValueError, 'First argument must be a toric variety.' + raise ValueError('First argument must be a toric variety.') if not base_ring in [ZZ,QQ]: - raise ValueError, 'Base ring must be either ZZ or QQ.' + raise ValueError('Base ring must be either ZZ or QQ.') key = tuple([toric_variety, base_ring]) extra = {'check':check} @@ -803,7 +803,7 @@ def __div__(self, other): ... NotImplementedError: Quotients of the Chow group are not implemented. """ - raise NotImplementedError, 'Quotients of the Chow group are not implemented.' + raise NotImplementedError('Quotients of the Chow group are not implemented.') def _repr_(self): @@ -824,7 +824,7 @@ def _repr_(self): elif self.base_ring() == ZZ: return "Chow group of " + str(self._variety) else: - raise(ValueError, 'Base ring must be QQ or ZZ.') + raise ValueError def __eq__(self, other): @@ -1188,7 +1188,7 @@ def _repr_(self): elif self._Chow_group.base_ring()==QQ: ring = 'Q' else: - raise NotImplementedError, 'Base ring must be ZZ or QQ.' + raise NotImplementedError('Base ring must be ZZ or QQ.') s = ['C' + str(x) for x in tors] if len(free)==1: diff --git a/src/sage/schemes/toric/divisor.py b/src/sage/schemes/toric/divisor.py index 4a028c6172c..8d8348b4c65 100644 --- a/src/sage/schemes/toric/divisor.py +++ b/src/sage/schemes/toric/divisor.py @@ -393,7 +393,7 @@ def base_extend(self, R): """ # This check prevents extension to cohomology rings via coercion if isinstance(R,CohomologyRing): - raise TypeError, 'Coefficient ring cannot be a cohomology ring.' + raise TypeError('Coefficient ring cannot be a cohomology ring.') if self.base_ring().has_coerce_map_from(R): return self elif R.has_coerce_map_from(self.base_ring()): diff --git a/src/sage/schemes/toric/homset.py b/src/sage/schemes/toric/homset.py index 37cdbf5f037..41958d07306 100644 --- a/src/sage/schemes/toric/homset.py +++ b/src/sage/schemes/toric/homset.py @@ -267,7 +267,7 @@ def _element_constructor_(self, x, check=True): from sage.schemes.toric.morphism import SchemeMorphism_fan_toric_variety return SchemeMorphism_fan_toric_variety(self, x, check=check) - raise TypeError, "x must be a fan morphism or a list/tuple of polynomials" + raise TypeError("x must be a fan morphism or a list/tuple of polynomials") def _an_element_(self): diff --git a/src/sage/schemes/toric/ideal.py b/src/sage/schemes/toric/ideal.py index 29e8e753f74..3a207a06db5 100644 --- a/src/sage/schemes/toric/ideal.py +++ b/src/sage/schemes/toric/ideal.py @@ -262,7 +262,7 @@ def __init__(self, A, if algorithm=='HostenSturmfels': ideal = self._ideal_HostenSturmfels() else: - raise ValueError, 'Algorithm = '+str(algorithm)+' is not known!' + raise ValueError('Algorithm = '+str(algorithm)+' is not known!') gens = [ ring(x) for x in ideal.gens() ] MPolynomialIdeal.__init__(self, ring, gens, coerce=False) diff --git a/src/sage/schemes/toric/variety.py b/src/sage/schemes/toric/variety.py index d9ca49850c1..993d87e230b 100644 --- a/src/sage/schemes/toric/variety.py +++ b/src/sage/schemes/toric/variety.py @@ -2119,7 +2119,7 @@ def volume_class(self): dim = self.dimension_relative() dVol = HH(self.fan().generating_cone(0)).part_of_degree(dim) if dVol.is_zero(): - raise ValueError, 'Volume class does not exist.' + raise ValueError('Volume class does not exist.') return dVol def integrate(self, cohomology_class): @@ -3208,7 +3208,7 @@ def __init__(self, variety): self._variety = variety if not variety.is_orbifold(): - raise NotImplementedError, 'Requires an orbifold toric variety.' + raise NotImplementedError('Requires an orbifold toric variety.') R = PolynomialRing(QQ, variety.variable_names()) self._polynomial_ring = R @@ -3585,7 +3585,7 @@ def exp(self): [1/2*z^2 + z + 1] """ if not self.part_of_degree(0).is_zero(): - raise ValueError, 'Must not have a constant part.' + raise ValueError('Must not have a constant part.') exp_x = self.parent().one() for d in range(1,self.parent()._variety.dimension()+1): exp_x += self**d / factorial(d) diff --git a/src/sage/server/trac/trac.py b/src/sage/server/trac/trac.py index 843ab5ed1db..b1296aa2620 100644 --- a/src/sage/server/trac/trac.py +++ b/src/sage/server/trac/trac.py @@ -53,7 +53,7 @@ def trac_create_instance(directory = 'sage_trac', easy_setup = False): e = os.system(cmd) if e: - raise RuntimeError, "Error creating trac environment." + raise RuntimeError("Error creating trac environment.") if easy_setup: conf_name = os.path.abspath(os.path.join(directory, 'conf/trac.ini')) diff --git a/src/sage/sets/integer_range.py b/src/sage/sets/integer_range.py index 0ac91257d3c..8dd5b083d05 100644 --- a/src/sage/sets/integer_range.py +++ b/src/sage/sets/integer_range.py @@ -272,7 +272,7 @@ def _element_constructor_(self, el): return Integer(el) return el else: - raise ValueError, "%s not in %s"%(el, self) + raise ValueError("%s not in %s"%(el, self)) element_class = Integer @@ -417,7 +417,7 @@ def rank(self,x): IndexError: 87 not in self """ if x not in self: - raise IndexError, "%s not in self"%x + raise IndexError("%s not in self"%x) return Integer((x - self._begin)/self._step) def __getitem__(self, i): @@ -589,7 +589,7 @@ def rank(self, x): IndexError: 22 not in self """ if x not in self: - raise IndexError, "%s not in self"%x + raise IndexError("%s not in self"%x) return Integer((x - self._begin)/self._step) def __getitem__(self, i): @@ -603,7 +603,7 @@ def __getitem__(self, i): -5 """ if isinstance(i,slice): - raise NotImplementedError, "not yet" + raise NotImplementedError("not yet") if isinstance(i, int): i = Integer(i) @@ -611,7 +611,7 @@ def __getitem__(self, i): raise ValueError if i < 0: - raise IndexError, "out of range" + raise IndexError("out of range") else: return self._begin + i * self._step diff --git a/src/sage/sets/non_negative_integers.py b/src/sage/sets/non_negative_integers.py index a1c9518a06a..94eb479423f 100644 --- a/src/sage/sets/non_negative_integers.py +++ b/src/sage/sets/non_negative_integers.py @@ -154,7 +154,7 @@ def _element_constructor_(self, i): if i in self: return self.from_integer(i) else: - raise ValueError, "Value %s in not in %s."%(i, self) + raise ValueError("Value %s in not in %s."%(i, self)) from_integer = Integer diff --git a/src/sage/sets/set.py b/src/sage/sets/set.py index 8fcc64baaf6..6f8e8b19ae2 100644 --- a/src/sage/sets/set.py +++ b/src/sage/sets/set.py @@ -126,7 +126,7 @@ def Set(X): return X if isinstance(X, Element): - raise TypeError, "Element has no defined underlying set" + raise TypeError("Element has no defined underlying set") elif isinstance(X, (list, tuple, set, frozenset)): return Set_object_enumerated(frozenset(X)) try: @@ -162,7 +162,7 @@ def EnumeratedSet(X): deprecation(8930, 'EnumeratedSet is deprecated; use Set instead.') try: if not X.is_finite(): - raise ValueError, "X (=%s) must be finite"%X + raise ValueError("X (=%s) must be finite"%X) except AttributeError: pass return Set_object_enumerated(X) @@ -408,7 +408,7 @@ def union(self, X): if self is X: return self return Set_object_union(self, X) - raise TypeError, "X (=%s) must be a Set"%X + raise TypeError("X (=%s) must be a Set"%X) def __add__(self, X): """ @@ -468,7 +468,7 @@ def intersection(self, X): if self is X: return self return Set_object_intersection(self, X) - raise TypeError, "X (=%s) must be a Set"%X + raise TypeError("X (=%s) must be a Set"%X) def difference(self, X): @@ -498,7 +498,7 @@ def difference(self, X): if self is X: return Set([]) return Set_object_difference(self, X) - raise TypeError, "X (=%s) must be a Set"%X + raise TypeError("X (=%s) must be a Set"%X) def symmetric_difference(self, X): r""" @@ -515,7 +515,7 @@ def symmetric_difference(self, X): if self is X: return Set([]) return Set_object_symmetric_difference(self, X) - raise TypeError, "X (=%s) must be a Set"%X + raise TypeError("X (=%s) must be a Set"%X) def __sub__(self, X): @@ -588,7 +588,7 @@ def cardinality(self): try: return len(self.__object) except TypeError: - raise NotImplementedError, "computation of cardinality of %s not yet implemented"%self.__object + raise NotImplementedError("computation of cardinality of %s not yet implemented"%self.__object) def is_empty(self): """ diff --git a/src/sage/stats/basic_stats.py b/src/sage/stats/basic_stats.py index a55217ec714..5a4fa5be600 100644 --- a/src/sage/stats/basic_stats.py +++ b/src/sage/stats/basic_stats.py @@ -393,7 +393,7 @@ def moving_average(v, n): return v.simple_moving_average(n)[n-1:] n = int(n) if n <= 0: - raise ValueError, "n must be positive" + raise ValueError("n must be positive") nn = ZZ(n) s = sum(v[:n]) ans = [s/nn] diff --git a/src/sage/stats/r.py b/src/sage/stats/r.py index 75832e0c65f..a047717a146 100644 --- a/src/sage/stats/r.py +++ b/src/sage/stats/r.py @@ -31,7 +31,7 @@ def ttest(x,y,conf_level = 0.95, **kw): 0.941026372027427 """ if len(x) != len(y): - raise AttributeError, "vectors x and y must be of same length" + raise AttributeError("vectors x and y must be of same length") test = myR.t_test(x,y,conf_level = conf_level, **kw)._sage_() t = test.get('DATA').get('p_value') diff --git a/src/sage/structure/factorization.py b/src/sage/structure/factorization.py index d9f59484b0c..f5a1a010079 100644 --- a/src/sage/structure/factorization.py +++ b/src/sage/structure/factorization.py @@ -290,16 +290,16 @@ def __init__(self, x, unit=None, cr=False, sort=True, simplify=True): (Ambient free module of rank 3 over the principal ideal domain Integer Ring)^2 """ if not isinstance(x, list): - raise TypeError, "x must be a list" + raise TypeError("x must be a list") for i in xrange(len(x)): t=x[i] if not (isinstance(t, tuple) and len(t) == 2): - raise TypeError, "x must be a list of pairs (p, e) with e an integer" + raise TypeError("x must be a list of pairs (p, e) with e an integer") if not isinstance(t[1],(int, long, Integer)): try: x[i]= (t[0], Integer(t[1])) except TypeError: - raise TypeError, "exponents of factors must be integers" + raise TypeError("exponents of factors must be integers") try: self.__universe = Sequence(t[0] for t in x).universe() @@ -360,7 +360,7 @@ def __setitem__(self, i, v): ... TypeError: 'Factorization' object does not support item assignment """ - raise TypeError, "'Factorization' object does not support item assignment" + raise TypeError("'Factorization' object does not support item assignment") def __len__(self): """ @@ -560,7 +560,7 @@ def base_change(self, U): try: return Factorization([(U(f[0]), f[1]) for f in list(self)], unit=U(self.unit())) except TypeError: - raise TypeError, "Impossible to coerce the factors of %s into %s"%(self, U) + raise TypeError("Impossible to coerce the factors of %s into %s"%(self, U)) def is_commutative(self): """ @@ -1068,7 +1068,7 @@ def __mul__(self, other): self = self.base_change(U) other = other.base_change(U) except TypeError: - raise TypeError, "Cannot multiply %s and %s because they cannot be coerced into a common universe"%(self,other) + raise TypeError("Cannot multiply %s and %s because they cannot be coerced into a common universe"%(self,other)) if self.is_commutative() and other.is_commutative(): d1 = dict(self) @@ -1110,7 +1110,7 @@ def __pow__(self, n): try: n = Integer(n) except TypeError: - raise TypeError, "Exponent n (= %s) must be an integer." % n + raise TypeError("Exponent n (= %s) must be an integer." % n) if n == 1: return self if n == 0: @@ -1207,7 +1207,7 @@ def gcd(self, other): Univariate Polynomial Ring in x over Integer Ring """ if not isinstance(other, Factorization): - raise NotImplementedError, "can't take gcd of factorization and non-factorization" + raise NotImplementedError("can't take gcd of factorization and non-factorization") if len(self) and len(other): try: @@ -1217,7 +1217,7 @@ def gcd(self, other): self = self.base_change(U) other = other.base_change(U) except TypeError: - raise TypeError, "Cannot take the gcd of %s and %s because they cannot be coerced into a common universe"%(self,other) + raise TypeError("Cannot take the gcd of %s and %s because they cannot be coerced into a common universe"%(self,other)) if self.is_commutative() and other.is_commutative(): d1 = dict(self) @@ -1227,7 +1227,7 @@ def gcd(self, other): s[a] = min(d1[a],d2[a]) return Factorization(list(s.iteritems())) else: - raise NotImplementedError, "gcd is not implemented for non-commutative factorizations" + raise NotImplementedError("gcd is not implemented for non-commutative factorizations") def lcm(self, other): r""" @@ -1249,7 +1249,7 @@ def lcm(self, other): Univariate Polynomial Ring in x over Integer Ring """ if not isinstance(other, Factorization): - raise NotImplementedError, "can't take lcm of factorization and non-factorization" + raise NotImplementedError("can't take lcm of factorization and non-factorization") if len(self) and len(other): try: @@ -1259,7 +1259,7 @@ def lcm(self, other): self = self.base_change(U) other = other.base_change(U) except TypeError: - raise TypeError, "Cannot take the lcm of %s and %s because they cannot be coerced into a common universe"%(self,other) + raise TypeError("Cannot take the lcm of %s and %s because they cannot be coerced into a common universe"%(self,other)) if self.is_commutative() and other.is_commutative(): d1 = dict(self) @@ -1269,7 +1269,7 @@ def lcm(self, other): s[a] = max(d1.get(a,0),d2.get(a,0)) return Factorization(list(s.iteritems())) else: - raise NotImplementedError, "lcm is not implemented for non-commutative factorizations" + raise NotImplementedError("lcm is not implemented for non-commutative factorizations") def is_integral(self): r""" @@ -1311,7 +1311,7 @@ def radical(self): ValueError: All exponents in the factorization must be positive. """ if not all([e > 0 for p,e in self.__x]): - raise ValueError, "All exponents in the factorization must be positive." + raise ValueError("All exponents in the factorization must be positive.") return Factorization([(p,1) for p,e in self.__x], unit=self.unit().parent()(1), cr=self.__cr, sort=False, simplify=False) def radical_value(self): @@ -1336,6 +1336,6 @@ def radical_value(self): ValueError: All exponents in the factorization must be positive. """ if not all([e > 0 for p,e in self.__x]): - raise ValueError, "All exponents in the factorization must be positive." + raise ValueError("All exponents in the factorization must be positive.") return prod([p for p,e in self.__x]) diff --git a/src/sage/structure/formal_sum.py b/src/sage/structure/formal_sum.py index 0d750367c1f..443fa91b4b4 100644 --- a/src/sage/structure/formal_sum.py +++ b/src/sage/structure/formal_sum.py @@ -302,7 +302,7 @@ def __init__(self, x, parent=formal_sums, check=True, reduce=True): try: self._data = [(k(t[0]), t[1]) for t in self._data] except (IndexError, KeyError) as msg: - raise TypeError, "%s\nInvalid formal sum"%msg + raise TypeError("%s\nInvalid formal sum"%msg) def __iter__(self): """ diff --git a/src/sage/structure/gens_py.py b/src/sage/structure/gens_py.py index 2ddec2871b7..c2725033115 100644 --- a/src/sage/structure/gens_py.py +++ b/src/sage/structure/gens_py.py @@ -28,7 +28,7 @@ def multiplicative_iterator(M): stop = list(M.generator_orders()) for i in range(len(stop)): if stop[i] is infinity: - raise ArithmeticError, "%s is not finite."%M + raise ArithmeticError("%s is not finite."%M) stop[i] = stop[i] - 1 n = 0 z = M(1) @@ -55,7 +55,7 @@ def abelian_iterator(M): stop = list(M.generator_orders()) for i in range(len(stop)): if stop[i] is infinity: - raise ArithmeticError, "%s is not finite."%M + raise ArithmeticError("%s is not finite."%M) stop[i] = stop[i] - 1 n = 0 z = M(0) diff --git a/src/sage/structure/list_clone_timings.py b/src/sage/structure/list_clone_timings.py index 7b1a3928782..c8d8cc5ce74 100644 --- a/src/sage/structure/list_clone_timings.py +++ b/src/sage/structure/list_clone_timings.py @@ -112,7 +112,7 @@ def check(self): """ for i in range(len(self)-1): if self[i] >= self[i+1]: - raise ValueError, "Lists is not increasing" + raise ValueError("Lists is not increasing") ##################################################################### diff --git a/src/sage/symbolic/assumptions.py b/src/sage/symbolic/assumptions.py index 393cb3ec4cf..bd28dc27415 100644 --- a/src/sage/symbolic/assumptions.py +++ b/src/sage/symbolic/assumptions.py @@ -114,7 +114,7 @@ def assume(self): # We get the list here because features may be added with time. valid_features = list(maxima("features")) if self._assumption not in [repr(x).strip() for x in list(valid_features)]: - raise ValueError, "%s not a valid assumption, must be one of %s" % (self._assumption, valid_features) + raise ValueError("%s not a valid assumption, must be one of %s" % (self._assumption, valid_features)) cur = maxima.get("context") self._context = maxima.newcontext('context' + maxima._next_var_name()) try: @@ -124,7 +124,7 @@ def assume(self): # raise ValueError, "Assumption is inconsistent" except RuntimeError as mess: if 'inconsistent' in str(mess): # note Maxima doesn't tell you if declarations are redundant - raise ValueError, "Assumption is inconsistent" + raise ValueError("Assumption is inconsistent") else: raise maxima.set("context", cur) @@ -411,7 +411,7 @@ def assume(*args): try: x.assume() except KeyError: - raise TypeError, "assume not defined for objects of type '%s'"%type(x) + raise TypeError("assume not defined for objects of type '%s'"%type(x)) def forget(*args): """ @@ -461,7 +461,7 @@ def forget(*args): try: x.forget() except KeyError: - raise TypeError, "forget not defined for objects of type '%s'"%type(x) + raise TypeError("forget not defined for objects of type '%s'"%type(x)) def assumptions(*args): """ diff --git a/src/sage/symbolic/callable.py b/src/sage/symbolic/callable.py index 0c5820bddef..7182f67527c 100644 --- a/src/sage/symbolic/callable.py +++ b/src/sage/symbolic/callable.py @@ -171,7 +171,7 @@ def __call__(self, R): Callable function ring with arguments (x, y) """ if R is not SR: - raise ValueError, "Can only make callable symbolic expression rings from the Symbolic Ring" + raise ValueError("Can only make callable symbolic expression rings from the Symbolic Ring") return CallableSymbolicExpressionRing(self.arguments()) def arguments(self): @@ -494,7 +494,7 @@ def create_key(self, args, check=True): args, = args for arg in args: if not is_SymbolicVariable(arg): - raise TypeError, "Must construct a function with a tuple (or list) of variables." + raise TypeError("Must construct a function with a tuple (or list) of variables.") args = tuple(args) return args diff --git a/src/sage/symbolic/constants.py b/src/sage/symbolic/constants.py index f2d8cdc7667..6f76834260c 100644 --- a/src/sage/symbolic/constants.py +++ b/src/sage/symbolic/constants.py @@ -1296,7 +1296,7 @@ def _mpfr_(self, R): """ if R.precision() <= self._bits: return R(self._value) - raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits) + raise NotImplementedError("%s is only available up to %s bits"%(self.name(), self._bits)) def _real_double_(self, R): """ @@ -1309,7 +1309,7 @@ def _real_double_(self, R): """ if R.precision() <= self._bits: return R(self._value) - raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits) + raise NotImplementedError("%s is only available up to %s bits"%(self.name(), self._bits)) def __float__(self): """ @@ -1322,7 +1322,7 @@ def __float__(self): """ if self._bits < 53: - raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits) + raise NotImplementedError("%s is only available up to %s bits"%(self.name(), self._bits)) return float(self._value) class Brun(LimitedPrecisionConstant): diff --git a/src/sage/symbolic/expression_conversions.py b/src/sage/symbolic/expression_conversions.py index d4fa603c3d1..48ed0d4ec56 100644 --- a/src/sage/symbolic/expression_conversions.py +++ b/src/sage/symbolic/expression_conversions.py @@ -70,7 +70,7 @@ def pyobject(self): ... TypeError: self must be a numeric expression """ - raise TypeError, 'self must be a numeric expression' + raise TypeError('self must be a numeric expression') def operands(self): """ @@ -295,7 +295,7 @@ def pyobject(self, ex, obj): ... NotImplementedError: pyobject """ - raise NotImplementedError, "pyobject" + raise NotImplementedError("pyobject") def symbol(self, ex): """ @@ -311,7 +311,7 @@ def symbol(self, ex): ... NotImplementedError: symbol """ - raise NotImplementedError, "symbol" + raise NotImplementedError("symbol") def relation(self, ex, operator): """ @@ -331,7 +331,7 @@ def relation(self, ex, operator): ... NotImplementedError: relation """ - raise NotImplementedError, "relation" + raise NotImplementedError("relation") def derivative(self, ex, operator): """ @@ -348,7 +348,7 @@ def derivative(self, ex, operator): ... NotImplementedError: derivative """ - raise NotImplementedError, "derivative" + raise NotImplementedError("derivative") def arithmetic(self, ex, operator): """ @@ -366,7 +366,7 @@ def arithmetic(self, ex, operator): ... NotImplementedError: arithmetic """ - raise NotImplementedError, "arithmetic" + raise NotImplementedError("arithmetic") def composition(self, ex, operator): """ @@ -383,7 +383,7 @@ def composition(self, ex, operator): ... NotImplementedError: composition """ - raise NotImplementedError, "composition" + raise NotImplementedError("composition") class InterfaceInit(Converter): def __init__(self, interface): @@ -748,7 +748,7 @@ def arithmetic(self, ex, operator): if base == e and expt / (pi*I) in QQ: return exp(expt)._algebraic_(self.field) - raise TypeError, "unable to convert %s to %s"%(ex, self.field) + raise TypeError("unable to convert %s to %s"%(ex, self.field)) def composition(self, ex, operator): """ @@ -780,7 +780,7 @@ def composition(self, ex, operator): rat_arg = (operand.imag()/(2*ex.parent().pi()))._rational_() if rat_arg == 0: # here we will either try and simplify, or return - raise ValueError, "Unable to represent as an algebraic number." + raise ValueError("Unable to represent as an algebraic number.") real = operand.real() if real: mag = exp(operand.real())._algebraic_(QQbar) @@ -811,7 +811,7 @@ def composition(self, ex, operator): #expression back. For example, QQbar(zeta(7)). See #ticket #12665. if cmp(res, ex) == 0: - raise TypeError, "unable to convert %s to %s"%(ex, self.field) + raise TypeError("unable to convert %s to %s"%(ex, self.field)) return self.field(res) def algebraic(ex, field): @@ -893,7 +893,7 @@ def __init__(self, ex, base_ring=None, ring=None): """ if not (ring is None or base_ring is None): - raise TypeError, "either base_ring or ring must be specified, but not both" + raise TypeError("either base_ring or ring must be specified, but not both") self.ex = ex if ring is not None: @@ -901,7 +901,7 @@ def __init__(self, ex, base_ring=None, ring=None): self.varnames = ring.variable_names_recursive() for v in ex.variables(): if repr(v) not in self.varnames and v not in base_ring: - raise TypeError, "%s is not a variable of %s" %(v, ring) + raise TypeError("%s is not a variable of %s" %(v, ring)) self.ring = ring self.base_ring = base_ring elif base_ring is not None: @@ -913,7 +913,7 @@ def __init__(self, ex, base_ring=None, ring=None): self.ring = PolynomialRing(self.base_ring, names=vars) self.varnames = self.ring.variable_names() else: - raise TypeError, "either a ring or base ring must be specified" + raise TypeError("either a ring or base ring must be specified") def symbol(self, ex): """ @@ -981,7 +981,7 @@ def relation(self, ex, op): if op == operator.eq: return self(ex.lhs()) - self(ex.rhs()) else: - raise ValueError, "Unable to represent as a polynomial" + raise ValueError("Unable to represent as a polynomial") def arithmetic(self, ex, operator): """ @@ -1191,7 +1191,7 @@ def symbol(self, ex): try: return self.ff.fast_float_constant(float(ex)) except TypeError: - raise ValueError, "free variable: %s" % repr(ex) + raise ValueError("free variable: %s" % repr(ex)) def arithmetic(self, ex, operator): """ diff --git a/src/sage/symbolic/function_factory.py b/src/sage/symbolic/function_factory.py index f01ceecb9c7..beb883a4cdd 100644 --- a/src/sage/symbolic/function_factory.py +++ b/src/sage/symbolic/function_factory.py @@ -85,7 +85,7 @@ def __reduce__(self): func = l.get(func_name+"_func", None) if func: if not callable(func): - raise ValueError, func_name + "_func" + " parameter must be callable" + raise ValueError(func_name + "_func" + " parameter must be callable") setattr(NewSymbolicFunction, '_%s_'%func_name, func) return NewSymbolicFunction() @@ -300,7 +300,7 @@ def function(s, *args, **kwds): 2*x """ if not isinstance(s, (str, unicode)): - raise TypeError, "expect string as first argument" + raise TypeError("expect string as first argument") # create the function if ',' in s: diff --git a/src/sage/symbolic/integration/external.py b/src/sage/symbolic/integration/external.py index 554d2e601e8..600b91da2c5 100644 --- a/src/sage/symbolic/integration/external.py +++ b/src/sage/symbolic/integration/external.py @@ -48,7 +48,7 @@ def mma_free_integrator(expression, v, a=None, b=None): # We need to integrate against x vars = [str(x) for x in expression.variables()] if any(len(x)>1 for x in vars): - raise NotImplementedError, "Mathematica online integrator can only handle single letter variables." + raise NotImplementedError("Mathematica online integrator can only handle single letter variables.") x = SR.var('x') if repr(v) != 'x': for i in range(ord('a'), ord('z')+1): @@ -67,4 +67,4 @@ def mma_free_integrator(expression, v, a=None, b=None): ans = ans.subs({x:v}).subs({shadow_x:x}) return ans except TypeError: - raise ValueError, "Unable to parse: %s" % mexpr + raise ValueError("Unable to parse: %s" % mexpr) diff --git a/src/sage/symbolic/integration/integral.py b/src/sage/symbolic/integration/integral.py index dc27706f763..6cb36a914c4 100644 --- a/src/sage/symbolic/integration/integral.py +++ b/src/sage/symbolic/integration/integral.py @@ -684,7 +684,7 @@ def integrate(expression, v=None, a=None, b=None, algorithm=None): if algorithm is not None: integrator = available_integrators.get(algorithm) if not integrator: - raise ValueError, "Unknown algorithm: %s" % algorithm + raise ValueError("Unknown algorithm: %s" % algorithm) return integrator(expression, v, a, b) if a is None: return indefinite_integral(expression, v) diff --git a/src/sage/symbolic/random_tests.py b/src/sage/symbolic/random_tests.py index 8b95e06ad64..f5384cb84ff 100644 --- a/src/sage/symbolic/random_tests.py +++ b/src/sage/symbolic/random_tests.py @@ -354,20 +354,20 @@ def assert_strict_weak_order(a,b,c, cmp_func): msg += str(cmp) for i in range(0,3): # irreflexivity - if cmp[i,i]: raise ValueError, msg + if cmp[i,i]: raise ValueError(msg) for i,j in indices: # asymmetric if i==j: continue #if x[i] == x[j]: continue - if cmp[i,j] and cmp[j,i]: raise ValueError, msg + if cmp[i,j] and cmp[j,i]: raise ValueError(msg) for i,j,k in Permutations([0,1,2]): # transitivity - if cmp[i,j] and cmp[j,k] and not cmp[i,k]: raise ValueError, msg + if cmp[i,j] and cmp[j,k] and not cmp[i,k]: raise ValueError(msg) def incomparable(i,j): return (not cmp[i,j]) and (not cmp[j,i]) for i,j,k in Permutations([0,1,2]): # transitivity of equivalence - if incomparable(i,j) and incomparable(j,k) and not incomparable(i,k): raise ValueError, msg + if incomparable(i,j) and incomparable(j,k) and not incomparable(i,k): raise ValueError(msg) def test_symbolic_expression_order(repetitions=100): r""" diff --git a/src/sage/symbolic/relation.py b/src/sage/symbolic/relation.py index a52a8cddff8..aa7ec1e0ffa 100644 --- a/src/sage/symbolic/relation.py +++ b/src/sage/symbolic/relation.py @@ -406,19 +406,19 @@ def test_relation_maxima(relation): try: s = m.parent()._eval_line('is (equal(%s,%s))'%(repr(m.lhs()),repr(m.rhs()))) except TypeError as msg: - raise ValueError, "unable to evaluate the predicate '%s'"%repr(relation) + raise ValueError("unable to evaluate the predicate '%s'"%repr(relation)) elif relation.operator() == operator.ne: # operator is not equal try: s = m.parent()._eval_line('is (notequal(%s,%s))'%(repr(m.lhs()),repr(m.rhs()))) except TypeError as msg: - raise ValueError, "unable to evaluate the predicate '%s'"%repr(relation) + raise ValueError("unable to evaluate the predicate '%s'"%repr(relation)) else: # operator is < or > or <= or >=, which Maxima handles fine try: s = m.parent()._eval_line('is (%s)'%repr(m)) except TypeError as msg: - raise ValueError, "unable to evaluate the predicate '%s'"%repr(relation) + raise ValueError("unable to evaluate the predicate '%s'"%repr(relation)) if s == 'true': return True @@ -756,7 +756,7 @@ def solve(f, *args, **kwds): try: f = [s for s in f if s is not True] except TypeError: - raise ValueError, "Unable to solve %s for %s"%(f, args) + raise ValueError("Unable to solve %s for %s"%(f, args)) if any(s is False for s in f): return [] @@ -771,7 +771,7 @@ def solve(f, *args, **kwds): s = m.to_poly_solve(variables) except TypeError as mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): - raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) + raise ValueError("Sage is unable to determine whether the system %s can be solved for %s"%(f,args)) else: raise @@ -917,7 +917,7 @@ def solve_mod(eqns, modulus, solution_dict = False): eqns = [eq if is_Expression(eq) else (eq.lhs()-eq.rhs()) for eq in eqns] modulus = Integer(modulus) if modulus < 1: - raise ValueError, "the modulus must be a positive integer" + raise ValueError("the modulus must be a positive integer") vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(key=repr) diff --git a/src/sage/symbolic/units.py b/src/sage/symbolic/units.py index c36b83d5525..30368a94b9f 100644 --- a/src/sage/symbolic/units.py +++ b/src/sage/symbolic/units.py @@ -1191,7 +1191,7 @@ def unitdocs(unit): if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: - raise ValueError, "No documentation exists for the unit %s."%unit + raise ValueError("No documentation exists for the unit %s."%unit) def is_unit(s): """ @@ -1313,7 +1313,7 @@ def convert(expr, target): for variable in coeff.variables(): if is_unit(str(variable)): - raise ValueError, "Incompatible units" + raise ValueError("Incompatible units") return coeff.mul(target, hold=True) @@ -1413,7 +1413,7 @@ def convert_temperature(expr, target): 98.6000000000000 """ if len(expr.variables()) != 1: - raise ValueError, "Cannot convert" + raise ValueError("Cannot convert") elif target == None or unit_to_type[str(target)] == 'temperature': from sage.misc.all import sage_eval expr_temp = expr.variables()[0] @@ -1430,4 +1430,4 @@ def convert_temperature(expr, target): elif target_temp == units.temperature.rankine: return a[3]*target_temp else: - raise ValueError, "Cannot convert" + raise ValueError("Cannot convert") diff --git a/src/sage/tensor/coordinate_patch.py b/src/sage/tensor/coordinate_patch.py index 30ca2d197ca..6280f38158a 100644 --- a/src/sage/tensor/coordinate_patch.py +++ b/src/sage/tensor/coordinate_patch.py @@ -99,14 +99,14 @@ def __init__(self, coordinates, metric = None): from sage.symbolic.ring import is_SymbolicVariable if not all(is_SymbolicVariable(c) for c in coordinates): - raise TypeError, "%s is not a valid vector of coordinates." % \ - coordinates + raise TypeError("%s is not a valid vector of coordinates." % \ + coordinates) self._coordinates = tuple(coordinates) dim = len(self._coordinates) if metric is not None: - raise NotImplementedError, "Metric geometry not supported yet." + raise NotImplementedError("Metric geometry not supported yet.") diff --git a/src/sage/tensor/differential_form_element.py b/src/sage/tensor/differential_form_element.py index 24bee2a84b5..91536c1c4b7 100644 --- a/src/sage/tensor/differential_form_element.py +++ b/src/sage/tensor/differential_form_element.py @@ -387,7 +387,7 @@ def __init__(self, parent, degree, fun = None): from sage.tensor.differential_forms import DifferentialForms if not isinstance(parent, DifferentialForms): - raise TypeError, "Parent not an algebra of differential forms." + raise TypeError("Parent not an algebra of differential forms.") RingElement.__init__(self, parent) @@ -435,11 +435,11 @@ def __getitem__(self, subscript): dim = self.parent().base_space().dim() if any([s >= dim for s in subscript]): - raise ValueError, "Index out of bounds." + raise ValueError("Index out of bounds.") if len(subscript) != self._degree: - raise TypeError, "%s is not a subscript of degree %s" %\ - (subscript, self._degree) + raise TypeError("%s is not a subscript of degree %s" %\ + (subscript, self._degree)) sign, subscript = sort_subscript(subscript) @@ -473,11 +473,11 @@ def __setitem__(self, subscript, fun): dim = self.parent().base_space().dim() if any([s >= dim for s in subscript]): - raise ValueError, "Index out of bounds." + raise ValueError("Index out of bounds.") if len(subscript) != self._degree: - raise TypeError, "%s is not a subscript of degree %s" %\ - (subscript, self._degree) + raise TypeError("%s is not a subscript of degree %s" %\ + (subscript, self._degree)) sign, subscript = sort_subscript(subscript) self._components[subscript] = sign*SR(fun) @@ -666,9 +666,8 @@ def _add_(self, other): return self if self._degree != other._degree: - raise TypeError, \ - "Cannot add forms of degree %s and %s" % \ - (self._degree, other._degree) + raise TypeError("Cannot add forms of degree %s and %s" % \ + (self._degree, other._degree)) sumform = DifferentialForm(self.parent(), self._degree) sumform._components = self._components.copy() @@ -876,7 +875,7 @@ def derivative(self, *args, **kwargs): """ if len(args) > 0 or len(kwargs) > 0: - raise ValueError, "Differentiation of a form does not take any arguments." + raise ValueError("Differentiation of a form does not take any arguments.") return self.diff() @@ -931,8 +930,8 @@ def wedge(self, other): """ if self.parent() != other.parent(): - raise TypeError, "unsupported operand parents for wedge: " +\ - "\'%s\' and \'%s\'" % (self.parent(), other.parent()) + raise TypeError("unsupported operand parents for wedge: " +\ + "\'%s\' and \'%s\'" % (self.parent(), other.parent())) output = DifferentialForm(self.parent(), self._degree + other._degree) if self._degree + other._degree > self.parent().ngens(): @@ -1044,7 +1043,7 @@ def abs(self): NotImplementedError: Absolute value not defined for differential forms. """ - raise NotImplementedError, "Absolute value not defined for differential forms." + raise NotImplementedError("Absolute value not defined for differential forms.") def leading_coefficient(self, cmp=None): @@ -1061,7 +1060,7 @@ def leading_coefficient(self, cmp=None): NotImplementedError: leading_coefficient not defined for differential forms. """ - raise NotImplementedError, "leading_coefficient not defined for differential forms." + raise NotImplementedError("leading_coefficient not defined for differential forms.") def leading_item(self, cmp=None): @@ -1078,7 +1077,7 @@ def leading_item(self, cmp=None): NotImplementedError: leading_item not defined for differential forms. """ - raise NotImplementedError, "leading_item not defined for differential forms." + raise NotImplementedError("leading_item not defined for differential forms.") def leading_monomial(self, cmp=None): @@ -1095,7 +1094,7 @@ def leading_monomial(self, cmp=None): NotImplementedError: leading_monomial not defined for differential forms. """ - raise NotImplementedError, "leading_monomial not defined for differential forms." + raise NotImplementedError("leading_monomial not defined for differential forms.") def leading_support(self, cmp=None): @@ -1112,7 +1111,7 @@ def leading_support(self, cmp=None): NotImplementedError: leading_support not defined for differential forms. """ - raise NotImplementedError, "leading_support not defined for differential forms." + raise NotImplementedError("leading_support not defined for differential forms.") def leading_term(self, cmp=None): @@ -1129,7 +1128,7 @@ def leading_term(self, cmp=None): NotImplementedError: leading_term not defined for differential forms. """ - raise NotImplementedError, "leading_term not defined for differential forms." + raise NotImplementedError("leading_term not defined for differential forms.") def trailing_coefficient(self, cmp=None): @@ -1146,7 +1145,7 @@ def trailing_coefficient(self, cmp=None): NotImplementedError: trailing_coefficient not defined for differential forms. """ - raise NotImplementedError, "trailing_coefficient not defined for differential forms." + raise NotImplementedError("trailing_coefficient not defined for differential forms.") def trailing_item(self, cmp=None): @@ -1163,7 +1162,7 @@ def trailing_item(self, cmp=None): NotImplementedError: leading_coefficient not defined for differential forms. """ - raise NotImplementedError, "leading_coefficient not defined for differential forms." + raise NotImplementedError("leading_coefficient not defined for differential forms.") def trailing_monomial(self, cmp=None): @@ -1180,7 +1179,7 @@ def trailing_monomial(self, cmp=None): NotImplementedError: trailing_monomial not defined for differential forms. """ - raise NotImplementedError, "trailing_monomial not defined for differential forms." + raise NotImplementedError("trailing_monomial not defined for differential forms.") def trailing_support(self, cmp=None): @@ -1197,7 +1196,7 @@ def trailing_support(self, cmp=None): NotImplementedError: trailing_support not defined for differential forms. """ - raise NotImplementedError, "trailing_support not defined for differential forms." + raise NotImplementedError("trailing_support not defined for differential forms.") def trailing_term(self, cmp=None): @@ -1214,7 +1213,7 @@ def trailing_term(self, cmp=None): NotImplementedError: trailing_term not defined for differential forms. """ - raise NotImplementedError, "trailing_term not defined for differential forms." + raise NotImplementedError("trailing_term not defined for differential forms.") def map_coefficients(self, f): @@ -1231,7 +1230,7 @@ def map_coefficients(self, f): NotImplementedError: map_coefficients not defined for differential forms. """ - raise NotImplementedError, "map_coefficients not defined for differential forms." + raise NotImplementedError("map_coefficients not defined for differential forms.") def map_item(self, f): @@ -1248,7 +1247,7 @@ def map_item(self, f): NotImplementedError: map_item not defined for differential forms. """ - raise NotImplementedError, "map_item not defined for differential forms." + raise NotImplementedError("map_item not defined for differential forms.") def map_support(self, f): @@ -1265,7 +1264,7 @@ def map_support(self, f): NotImplementedError: map_support not defined for differential forms. """ - raise NotImplementedError, "map_support not defined for differential forms." + raise NotImplementedError("map_support not defined for differential forms.") diff --git a/src/sage/tensor/differential_forms.py b/src/sage/tensor/differential_forms.py index 4ccf6b9c3d0..503366fc45c 100644 --- a/src/sage/tensor/differential_forms.py +++ b/src/sage/tensor/differential_forms.py @@ -103,8 +103,7 @@ def __init__(self, coordinate_patch = None): coordinate_patch = CoordinatePatch((x, y, z)) if not isinstance(coordinate_patch, CoordinatePatch): - raise TypeError, \ - "%s not a valid Coordinate Patch" % coordinate_patch + raise TypeError("%s not a valid Coordinate Patch" % coordinate_patch) self._patch = coordinate_patch ParentWithGens.__init__(self, SR, \ @@ -267,8 +266,7 @@ def _element_constructor_(self, fun): fun = SR(fun) if fun not in self: - raise ValueError, \ - "Function not an element of this algebra of differential forms." + raise ValueError("Function not an element of this algebra of differential forms.") return DifferentialForm(self, 0, fun) diff --git a/src/setup.py b/src/setup.py index 9cba5b33c8c..9b2856c77ef 100644 --- a/src/setup.py +++ b/src/setup.py @@ -367,10 +367,9 @@ def build_extensions(self): def prepare_extension(self, ext): sources = ext.sources if sources is None or type(sources) not in (ListType, TupleType): - raise DistutilsSetupError, \ - ("in 'ext_modules' option (extension '%s'), " + + raise DistutilsSetupError(("in 'ext_modules' option (extension '%s'), " + "'sources' must be present and must be " + - "a list of source filenames") % ext.name + "a list of source filenames") % ext.name) sources = list(sources) fullname = self.get_ext_fullname(ext.name)