0

This is a curiosity. Say I am using IPython interactively, which by default imports

from numpy import sum

and after that I decide to use sum from the standard library. Say, to do something like

texts = [['a','good','day'],['a','lovely','day']]
sum(texts, [])

Can I do that? How?

  • Notice that I don't need a solution for flattening a list. I want a general solution for importing the standard library as if I were importing any other library, or a way to circumvent the shadowing of a function.
dmvianna
  • 15,088
  • 18
  • 77
  • 106

1 Answers1

2

You can access it under __builtin__ (Python 2) or builtins (Python 3):

>>> from numpy import sum
>>> texts = [['a','good','day'],['a','lovely','day']]
>>> sum(texts, [])
Traceback (most recent call last):
[...]
TypeError: cannot perform reduce with flexible type
>>> __builtin__.sum(texts, [])
['a', 'good', 'day', 'a', 'lovely', 'day']
>>> from __builtin__ import sum
>>> sum(texts, [])
['a', 'good', 'day', 'a', 'lovely', 'day']

But two points:

(1) IPython does not import numpy's sum by default-- unless you're working in a legacy pylab mode, in which case you shouldn't. :-)

(2) sum isn't a great example because using sum(something, []) to concatenate lists will show quadratic behaviour and so should generally be avoided.

DSM
  • 342,061
  • 65
  • 592
  • 494