0

I am trying the following:

>>> i = iter([1,2,3])
>>> print(type(i))
<class 'list_iterator'>
>>> print(type(i).mro())
[<class 'list_iterator'>, <class 'object'>]
>>> j = list_iterator()

and the last lines gives me an error:

Traceback (most recent call last):
  File "/home/pru/ML/stepik/examples module2/iterators.py", line 10, in <module>
    j = list_iterator()
NameError: name 'list_iterator' is not defined

How come it is not defined? Wouldn't interpreter look for name 'list_iterator' in 'object' namespace?

8
  • 1
    Because it's not one of the built-in functions that are exposed to you; you'd have to access it via type(i) instead, but what were you hoping to do with it? Commented Feb 21, 2021 at 8:38
  • 1
    by j = list_iterator() I was trying to create an instance of a list_iterator class. I am just playing around while learning Python. Commented Feb 21, 2021 at 8:41
  • But to what end, what were you going to do with j? What values did you expect to get from iterating over it? Commented Feb 21, 2021 at 8:42
  • 1
    nothing, just curiosity Commented Feb 21, 2021 at 8:42
  • so, how can I create an instance of this class? list_iterator is a class, right? Commented Feb 21, 2021 at 8:44

2 Answers 2

2

"Wouldn't interpreter look for name 'list_iterator' in 'object' namespace?" that's not how it works. object is a class, not a namespace, and list_iterator is a subclass of object, but that doesn't mean it must be accessable to us.

In most cases, you don't need to use list_iterator, that's why it's not exposed to us, but if you really need it, you can use it by defining it like so:

list_iterator = type(iter([]))
Sign up to request clarification or add additional context in comments.

2 Comments

so, there are classes that are actually defined but not accessible?
@prupru yes, another example is NoneType. This is not exclusive to built-ins, you can define a type in a file A.py, define a function that returns an instance of that class in B.py, and import that function in C.py, now in C.py you have an instance of a class you don't have access to (as long as you only import B.py and not A.py)
-1
i = iter([1,2,3])
print(i)
print(type(i))
print(type(i).mro())
print(next(i))
print(next(i))
print(next(i))
list_iterator = type(i)
print(list_iterator)

**> <list_iterator object at 0x7fa1763262b0> <class 'list_iterator'>

[<class 'list_iterator'>, <class 'object'>] 1 2 3 <class > 'list_iterator'>**

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.