Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Python (http://www.chiefdelphi.com/forums/forumdisplay.php?f=187)
-   -   "compiler" constants (http://www.chiefdelphi.com/forums/showthread.php?t=108447)

Ether 17-09-2012 17:16

"compiler" constants
 

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:

Code:

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

Re: "compiler" constants
 
Quote:

Originally Posted by Ether (Post 1186038)
...............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

Re: "compiler" constants
 
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 to simulate enums).

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

Code:

>>> 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.

Code:

>>> 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 has a reasonable set of answers about Python's scoping rules.

Ether 18-09-2012 08:11

Re: "compiler" constants
 
Quote:

Originally Posted by virtuald (Post 1186090)
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.




All times are GMT -5. The time now is 19:50.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi