Does Python provide "free" default iterators? [duplicate] - python

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does defining getitem on a class make it iterable in python?
I have a class that is basically a wrapper for a python list. Within this class I have defined __getitem__, __setitem__, and __len__ . I have not defined __iter__ for this class.
when I go:
thing = ListWrapper(range(4))
for i in thing :
print i
I get the output:
0
1
2
3
Which is nice, but I expected an error message of some sort saying that python could not find an iterator. I've given the documentation a look and can't find anything referencing default iterators. Furthermore, tracing through the code in PyDev shows that it is calling the __getitem__ method each iteration.
I was wondering if it is good practice to depend on this behavior in my code. It doesn't fell quite right to me at this point. Does Python guarantee that classes with __getitem__ and __len__ will be treated as if they have a defined iterator? Any other information on weirdness this may cause is also welcome.

If a class doesn't have __iter__, but does have __getitem__, the iteration machinery will call it with consecutive integers until it runs out.

Related

Understanding how Python builtins are mapped to underlying C implementation [duplicate]

This question already has answers here:
PyCharm, what is python_stubs?
(2 answers)
Finding the source code for built-in Python functions?
(8 answers)
Closed 1 year ago.
If I go to the implementation of let's say the next() builtin function, I'm forwarded to the builtins.py module to following code:
def next(iterator, default=None): # real signature unknown; restored from __doc__
"""
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""
pass
Now, it looks like this functions does nothing but obviously that's not the case.
I understand that this function is implemented in C under the hood, but how and when is this function(or other builtin functions) mapped to the underlying C implementation?
If you have an answer to this question, can you please also provide links that I can read in order to better unterstand this topic?
I'm not asking, where the code is, but how and when the function is mapped to that code
Thank you.

difference between the next function and the next method [duplicate]

This question already has answers here:
Python: Why should I use next() and not obj.next()?
(3 answers)
Closed 6 years ago.
When you make a generator by calling a function or method that has the yield keyword in it you get an object that has a next method.
So far as I can tell, there isn't a difference between using this method and using the next builtin function.
e.g. my_generator.next() vs next(my_generator)
So is there any difference? If not, why are there two ways of calling next on a generator?
In Python 2 the internal method for an iterator is next() in Python 3 it is __next__(). The builtin function next() is aware of this and always calls the right method making the code compatible with both versions. Also it adds the default argument for more easy handling of the iteration end.

How methods work in python? [duplicate]

This question already has an answer here:
python string module vs str methods
(1 answer)
Closed 6 years ago.
I am new to programming therefore may sound idiotic. I am learning python where I am not able to understand how few methods like upper(), split() etc work.
I mean you directly use like below:
"ABC".upper() or "abc,xyz".split(",")
Or, you can first import string and then call these methods like below:
import string
string.upper("abc")
string.split("abc,xyz", ",")
What is the difference, and how would we import string module when we can achieve the same output without importing it.
Are there similar cases exist apart from string module?
In fact, one of the paradigm you can use in Python is the Object Oriented Programming, where you modify object state through "methods" like this: myobject.mymethod().
Syntactically, it means that the first argument of the method mymethod() is in fact the object itself. But, as Python want also to deal with other paradigms (functional programming, imperative programming, and so on), there is two syntactical ways to address this method.
One is simply as I mentioned before: myobject.mymethod(), and the other one is simply to consider that the first argument is the object itself: mymethod(myobject).
More precisely, you can realize that when you define by yourself a method because you have to specify the first argument by self which is a reference to the object itself like this:
def mymethod(self):
pass

Why is iter not a method of an instance and __iter__ is? [duplicate]

This question already has answers here:
Why does Python code use len() function instead of a length method?
(7 answers)
Closed 8 years ago.
The "intuitive" way of getting an iterator for someone who usually programs in Java, C++, etc is something like list.iterator().
Why did the Python folks choose to have it as a general function like len() (which results in iter(list) rather than list.iter())?
The same question can be asked for the length of a construct as well (len()).
iter() supports different types of objects.
You can pass in either a sequence (supporting length and item access) or an iterable (which produces an iterator by calling obj.__iter__()) or an iterator (which returns self from __iter__).
The Java list.iter() then is served by list.__iter__() in Python, but the iter() function allows for more types. You can customise the behaviour with a __iter__ method but if you implemented a sequence instead, things will still work.
There is also a second form of the function where a callable and a sentinel are passed in:
iter(fileobj.readline, '')
iterates over a file object by calling the readline() method until it returns an empty string (equal to the second argument, the sentinel).
Then there is the Principle of Least Astonishment argument; iter() gives the standard library a stable API call to standardise on, just like operators do; no need to look up the documentation of the class to see if it implemented obj.iter() or obj.iterator() or obj.get_iterator().

Declaring functions in a class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python 'self' explained
I am a beginner in Python. I was going through the tutorials on Classes and Iterators when I had a doubt that I was unable to explain to myself. The program text below was a part of a class which calculates area.
def __init__(self,len,wid):
self.length=len
self.width=wid
def calculate_area(self)
return self.length*self.width
def print_area(self)
print 'Area='+str(self.calculate_area())
What I am unable to understand is why do the function's argument list have "self"? What is its role? Why are every variable resolved with "self"?
This is similar to this pointer in C++ (if you have come from C++ background)
Typical usage would be that the members of objects can be referenced by self in case if there is an ambiguity. e.g.
def calculate_area(self, length)
return self.length*self.width
Above length is an argument for calculate_area function.
if the object also has length member then it can be resolved by using self.length
Refer existing answer here:
What is the purpose of self?
I really don't know I'm too new on the Python world but I think that Python does not provide the this value as C# or Java do, so this is the mechanism that Python use to define itself in its classes.
Anyway you can see that you don't need to pass the self as parameter in the function call, because Python does for you.
This is my theory, but I'm also interested to know it so If anyone can say more about this, I think we will be very thankfull.
See you!

Categories

Resources