Re:Python: Common Newbie Mistakes, Part 1
by nknighthb on Saturday July 06, 2013 @08:43PM
(#6000580)
A simple fix to the time/now example is also useful for demonstrating first-class functions:
[ Parent
| on HN ]
The classic way is:
def print_now(now=None):
now = now or time.time()
print nowI hope "now" is never 1970-01-01 00:00:00.
Edit:
if now is None:
now = time.time()Or even more paranoid:
import mock
def print_now(now=mock.sentinel.now): now = now if now != mock.sentinel.now else time.time()
I don't have experience with mock, but I've used object() -- literally -- as a sentinel.
_sentinel = object()
def print_now(now=_sentinel):
if now is _sentinel:
now = time.time()
...if I recall, this is how SQLAlchemy does default values that are functions.