Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #100185

Shadowing built-ins [was Re: filter a list of strings]

From Steven D'Aprano <steve+comp.lang.python@pearwood.info>
Date 2015-12-09 18:38 +1100
Subject Shadowing built-ins [was Re: filter a list of strings]
Newsgroups comp.lang.python
References <3p9zlt5t5Vz5vN5@dovecot03.posteo.de> <mailman.171.1449145727.14615.python-list@python.org> <2598115.t018ozAsXX@PointedEars.de>
Followup-To comp.lang.python
Message-ID <5667da63$0$14486$c3e8da3@news.astraweb.com> (permalink)
Organization Unlimited download news at news.astraweb.com

Followups directed to: comp.lang.python

Show all headers | View raw


On Wednesday 09 December 2015 09:58, Thomas 'PointedEars' Lahn wrote:

> Mark Lawrence wrote:
> 
>> On 03/12/2015 01:15, c.buhtz@posteo.jp wrote:
>>> I would like to know how this could be done more elegant/pythonic.
>>>
>>> I have a big list (over 10.000 items) with strings (each 100 to 300
>>> chars long) and want to filter them.
>>>
>>> list = .....
>>> […]
[...]
> However, “list” is a built-in class/constructor that would be overwritten
> this way.  One should choose another identifier than “list” for one’s
> variables.

Correct, well mostly correct.

The original built-in list is *not* overridden, as such, but shadowed: it 
still exists, but access to it is blocked by the local variable "list". The 
list *type* still exists, only the *name* list is shadowed. So you can 
easily recover from accidentally shadowing the name by deleting the local:

del list

To beginners, accidental shadowing of built-ins is a serious source of 
confusion. But to experts, intentional shadowing can be useful.

There's nothing wrong with (say):

def sort_and_pop(list):
    list.sort()
    list.pop(0)

Yes, the local "list" shadows the built-in list. So what?

More usefully, one can monkey-patch a module by shadowing a built-in in that 
module:

# Python 3 only.
import builtins
def print(*args, **kwargs):
    log_something()
    builtins.print(*args, **kwargs)




-- 
Steve

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: filter a list of strings Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-12-03 12:28 +0000
  Re: filter a list of strings Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-12-08 23:58 +0100
    Shadowing built-ins [was Re: filter a list of strings] Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-12-09 18:38 +1100
    Re: filter a list of strings Sivan Greenberg <sivan@vitakka.co> - 2015-12-09 16:35 +0200

csiph-web