Ask Your Question

Revision history [back]

Check if a variable is assumed to be integer

I found a 'nice and clean' way to check if a variable is assumed to be integer.

The only objection to calling it 'nice and clean' is that it uses the hidden attribute_assumption, which does not exist as a method. This could be a feature request, and it would not be hard to implement.

In short, this checks if the variable 'a' is assumed to be integer:

sage: a = var('a')
sage: assume(a, 'integer')
sage: 'integer' in (x._assumption for x in assumptions(a))
True

(Tested in Sage Version 6.3.beta5, released on 2014-07-01, but I'm sure this has been possible for a long time.)

How could one find that out?

How could one find out about this? By exploring Sage using tab-completion and introspection.

sage: version() # for reference
'Sage Version 6.3.beta5, Release Date: 2014-07-01'
sage: a = var('a')
sage: assume(a, 'integer')
sage: h = assumptions()
sage: h
[a is integer]
sage: ha = assumptions(a)
sage: ha
[a is integer]
sage: d = assumptions(a)[0]
sage: d
a is integer
sage: type(d)
<class 'sage.symbolic.assumptions.GenericDeclaration'>

Now use the 'tab' key to check what methods are available for d:

sage: d.
d.assume       d.contradicts  d.dump         d.forget       d.rename       d.save         
d.category     d.db           d.dumps        d.has          d.reset_name   d.version

and keep exploring:

sage: d.has(a)
True
sage: from sage.symbolic.assumptions import GenericDeclaration as GDecl

Read the documentation for GDecl, then the source code.

sage: GDecl?
sage: GDecl??

and detect the use of the _assumption attribute in the source code. Now play with it!

sage: d._assumption
'integer'
sage: 'integer' in (x._assumption for x in assumptions(a))
True

Possible feature requests

This is beyond the scope of answering your question, but just in case someone finds it interesting and wants to open a trac ticket or two and/or change the code accordingly.

  • a method 'assumptions' for the class sage.symbolic.assumptions.GenericDeclaration.

  • make the is_integer method check for the 'integer' assumption as above, for symbolic variables. So far:

    sage: a.is_integer()
    False
    

    However the source code for this method is

    def is_integer(self):
        """
        Return True if this expression is known to be an integer.
    
        EXAMPLES::
    
            sage: SR(5).is_integer()
            True
        """
        return self._gobj.info(info_integer)
    

    in particular the docstring claims it should return True if the expression is known to be an integer.