Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iter() not working with datetime.now()

A simple snippet in Python 3.6.1:

import datetime j = iter(datetime.datetime.now, None) next(j) 

returns:

Traceback (most recent call last):   File "<stdin>", line 1, in <module> StopIteration 

instead of printing out the classic now() behavior with each next().

I've seen similar code working in Python 3.3, am I missing something or has something changed in version 3.6.1?

like image 597
Vidak Avatar asked May 31 '17 11:05

Vidak


People also ask

How do you fix AttributeError module datetime has no attribute now?

The error "AttributeError module 'datetime' has no attribute 'now'" occurs when we try to call the now method directly on the datetime module. To solve the error, use the following import import datetime and call the now method as datetime. datetime. now() .

How do I get the current time in python?

To get both current date and time datetime. now() function of DateTime module is used. This function returns the current local date and time.

How do I get the date in python?

Get the current date using date.The today() method of date class under DateTime module returns a date object which contains the value of Today's date.


1 Answers

This is definitely a bug introduced in Python 3.6.0b1. The iter() implementation recently switched to using _PyObject_FastCall() (an optimisation, see issue 27128), and it must be this call that is breaking this.

The same issue arrises with other C classmethod methods backed by Argument Clinic parsing:

>>> from asyncio import Task >>> Task.all_tasks() set() >>> next(iter(Task.all_tasks, None)) Traceback (most recent call last):   File "<stdin>", line 1, in <module> StopIteration 

If you need a work-around, wrap the callable in a functools.partial() object:

from functools import partial  j = iter(partial(datetime.datetime.now), None) 

I filed issue 30524 -- iter(classmethod, sentinel) broken for Argument Clinic class methods? with the Python project. The fix for this has landed and is part of 3.6.2rc1.

like image 77
Martijn Pieters Avatar answered Sep 21 '22 17:09

Martijn Pieters