How do I know if a value is eternal in Python?

Asked

Viewed 714 times

5

How can I check in Python if a certain value is eternal?

What determines that a particular type can be eternal?

For example, how to find out this in the case below?

a = 1 
b = 'Uma string'
c = [1, 2, 3]
d = xrange(1, 10)
e = range(1, 10)
f = {"a" : 1}
g = True

2 answers

6


I haven’t seen any article or document citing exactly how to do this "great". Meanwhile, the Miku, of Stackoverflow in English, cited some examples.

You can try something like:

1- Assuming the object is always iterable and then capturing the error if it is not, in style Pythonico - EAFP (Easier to Ask Forgiveness than Permission) - "better to ask forgiveness than permission"

try:
    _ = (e for e in my_object)
except TypeError:
    print my_object, 'is not iterable'

Or:

2- Using the module collections

import collections

if isinstance(e, collections.Iterable):
    # e is iterable

4

Two Pythonic Ways to Check This.

With try-except

try:
    iterator = iter(var)
except TypeError:
    # não iterável
else:
    # iterável

Checking by abstract class

Only works with classes new style - which do not exist in versions smaller than 2.2.

import collections

if isinstance(var, collections.Iterable):
    # iterável
else:
    # não iterável
  • 1

    Correction - the Newstyle classes exist yes since Python 2.2 and that’s what you get when you inherit your class from object. In practice any time after 2005 that does not use new style classes is wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.