views:

212

answers:

3

I have a method:

def foo(bar):
   # ...

Is there a way to mark bar as constant? Such as "The value in bar cannot change" or "The object pointed to by bar cannot change".

+2  A: 

No.

What's the point? If you're writing the function, isn't it up to you to make sure bar doesn't change? Or if you're calling the function, who cares?

Nikhil Chelliah
It is often a useful matter of policy - you are informing the user about a limitation of your function. Of course, this doesn't make as much sense in Python as there aren't prototypes, and there's no static compiler to enforce the constraint either.
Nick Bastin
The point is to help the programmer avoid making mistakes, to the extent possible. Otherwise we would all write everything in assembly.
Jeremy Friesner
@Jeremy Friesner: In Python, the "correct" way to do this is to just write a comment then.
carl
The problem with comments is that the language doesn't enforce them. So not only will they not detect or report the problem, they can serve to actively prevent a reader from seeing the problem, if the reader sees the comment and assumes it is true, when it isn't.
Jeremy Friesner
@Jeremy Friesner: Why should Python allow declarations of immutability when it doesn't even allow declarations of type? Type declarations would also "help the programmer avoid mistakes," but it's shunned in Python, too. Rely on tests, not on declarations.
Nikhil Chelliah
+3  A: 

If bar is an inmutable object, bar won't change during the function.

You can also create your own constant object. The recipie here.

razpeitia
You beat me to it.
wheaties
Note that intercepting modifications doesn't solve the problem on its own. How do you know that the client code won't encounter a ConstError? Only with sufficient testing.
Nikhil Chelliah
A: 

def foo(bar): pass

def foobar(): foo(bar)

Slartibartfast