The content of this blog is my personal opinion only. Although I am an employee - currently of Nvidia, in the past of other companies such as Iagination Technologies, MIPS, Intellectual Ventures, Intel, AMD, Motorola, and Gould - I reveal this only so that the reader may account for any possible bias I may have towards my employer's products. The statements I make here in no way represent my employer's position, nor am I authorized to speak on behalf of my employer. In fact, this posting may not even represent my personal opinion, since occasionally I play devil's advocate.

See http://docs.google.com/View?id=dcxddbtr_23cg5thdfj for photo credits.

Friday, May 20, 2016

less than function Block scope in Python

Block scope in Python - Stack Overflow: "No, there is no [python] language support for creating block scope. The only means to create scope is functions, classes or modules."
Someone else goes on to say: "The idiomatic way in Python is to keep your functions short. If you think you need this, refactor your code! :) "
I could very much like Python - but whenever I try to use it, I run into things like this very quickly.

I like Python's use of indentation.

But I imagine that the reasoning runs like this:
  • Python uses indentation and hence doesn't need {...} to provide blocks for constructs like IF, functions, etc.
  • But since Python doesn't have {...} blocks, we have no way to provide lexial scope except for def: and class: and modules.
  • "Who needs it anyway?" says the chorus of unimaginative twerps. "Just refactor".
So think about refactoring: you could introduce a function with def, and then call it immediately.  Must make sure tat the function cannot be called from elsewhere, but Python allowing local definitions (not-quite-closures) is sufficient for that. But that requires typing the name in twice.  

I have been doing the following in some python code:
if 1:
when I want to emphasize the relatedness of statements3.1 and 3.2.

The equivalent of 
in Perl or C.

(Amusingly, emacs often requires me if add an if(1) to the blocks {}.  It doesn't like indented "blocks in space".  After all, what crazy person would want to create lots of local blocks?)

I like indicating the relatedness.

Plus, if I need a temporary variable or to import a function, I like to be able to do so in the smallest scope possible.

Yes, it can be refactored to be a function that is immediately invoked.  But that is repetitive.

This explores aspects of one of my rules "The most important thing in programming is the ability to give something a name.  The second most important thing is to not be required to give something a name."

Python requires scopes to have names.   It fails the second most important test.


The obvious way to support scopes in an indentation oriented language like Python would be:

i.e. introduce a keyword "scope" or the like.

1 comment:

Andy "Krazy" Glew said...
This comment has been removed by the author.