Log in

View Full Version : "compiler" constants


Ether
17-09-2012, 17:16
New to Python. Have what I hope is a simple question.

I realize Python is interpreted, but I was wondering if there is something in Python equivalent to "compiler constants".

To illustrate with a very simple example, suppose I have a function:

def MyFunc(x)
return a*x^2 + b*x + c

... and I want to pass this function as an argument to a library function which is expecting only one argument (i.e "x").

Can I assign constant values to "a" "b" and "c" and have the interpreter literally replace all occurrences with the numerical values?

Ether
17-09-2012, 18:41
...............click for context^

Here is what I found, to my surprise:

I can simply assign values to variables a, b, and c:

a = 2
b = 3
c = 1

... and somehow when I pass MyFunc(x) to the library function as a parameter, it works.

It had not expected it to.

Does anybody know how this works "under the hood" ?

virtuald
18-09-2012, 00:43
As you've found out, there are no such things as constants in Python.

There are other oddities that people used to other languages find weird at first. No such thing as private variables in a class or module. Just about everything happens to be a variable of some kind. No enums (though there are neat tricks (http://stackoverflow.com/a/1695250) to simulate enums).

For fun, you can also define functions inside other functions:


>>> def some_fn():
... x = 1
... def _some_other_fn():
... print x
... _some_other_fn()
...
>>> some_fn()
1


Functions can actually be treated like variables too.


>>> def fn():
... pass
...
>>> x = fn
>>> x
<function fn at 0x7ffe4c917578>
>>> x.y = 1
>>> x
<function fn at 0x7ffe4c917578>
>>> x.y
1


But, to actually answer your question, this SO post (http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules) has a reasonable set of answers about Python's scoping rules.

Ether
18-09-2012, 08:11
For fun, you can also define functions inside other functions

You can do this in Delphi too. It can be a helpful way to organize code and make it more readable.