Awful code of the week

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 9 01:20:28 EDT 2016


On Tuesday 09 August 2016 13:59, Chris Angelico wrote:

> On Tue, Aug 9, 2016 at 1:46 PM, Rick Johnson
> <rantingrickjohnson at gmail.com> wrote:
>> On Sunday, August 7, 2016 at 1:54:51 AM UTC-5, Steven D'Aprano wrote:
>>> Seen in the office IRC channel:
>>>
>>>
>>> (13:23:07) fred:     near_limit = []
>>> (13:23:07) fred:     near_limit.append(1)
>>> (13:23:07) fred:     near_limit = len(near_limit)
>>> (13:23:09) fred: WTF
>>
>> Sure, this code smells of nauseous superfluity, but what
>> comes after these three lines? Is this _all_ there is? Or
>> are these three lines merely the initial setup stage for a
>> complex looping algorithm? Cherry picking a few lines from a
>> script and then judging them "unworthy", would not be a
>> fair. We should never attempt to purposely mimic the abysmal
>> state of justice in the USA.
> 
> I agree. There's nothing wrong with that code. I routinely have
> constructs like this:
> 
>     def register(self, obj):
>         self.files.append(obj)
>         return None
>         return None # just in case
>         return None

That's buggy. It should be:

    def register(self, obj):
        self.files.append(obj)
        return None and None or None
        return None # just in case
        return None

That way you're protected in case the boolean value of None is ever changed.



>     def process(self, stuff):
>         files = self.files
>         files = [] # to save memory
>         files = self.files
>         for file in files:
>             file.process(stuff)
>         return 1

    def process(self, stuff):
        try:
            files = self.files
            del files  # to save memory
            files = []  # just to be sure
            files = self.files
            for file in files:
                file.process(stuff)
            return 1
        finally:
            del files
            del file
            del stuff
            del self  # this has to come last


You can't be too careful with memory management.




-- 
Steve




More information about the Python-list mailing list