How to assign a default constant value in a function declaration

Peter Otten __peter__ at web.de
Mon Apr 5 08:43:45 EDT 2004


rzed wrote:

> "Vineet Jain" <vineet at eswap.com> wrote in
> news:mailman.341.1081121191.20120.python-list at python.org:
> 
>> The following does not work although it seems like something you
>> should be able to do.
>> 
>> def someFunction(option=Constants.DEFAULT_VALUE):
>> 
> Do you mean in a context like this?
> 
>>>> class Const:
> ...    someVal=255
> ...    otherVal=0
> ...
>>>> Const.someVal
> 255
>>>> someVal=255
>>>> someVal
> 255
>>>> def blip(Const.someVal):
>   File "<stdin>", line 1
>     def blip(Const.someVal):
>                   ^
> SyntaxError: invalid syntax
>>>> def blip(someVal):
> ...    (no syntax error)
> 
> 
> I've wondered about that, too.

Stop wondering then: 

>>> class Constants:
...     DEFAULT_VALUE = 42
...
>>> def someFunction(option=Constants.DEFAULT_VALUE):
...     print "option =", option
...
>>> someFunction(1)
option = 1
>>> someFunction()
option = 42
>>> Constants.DEFAULT_VALUE = "another value"
>>> someFunction()
option = 42
>>> Constants = None
>>> someFunction()
option = 42

Here Constants might also be a module. The only constraint is that
Constants.DEFAULT_VALUE is bound when the function is defined, not when
it's called.

Peter




More information about the Python-list mailing list