We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Is it possible and if so, what is the proper way to create a global library?
If I have (my_lib.py):
foo = 1
def init():
global foo
foo += 5
print foo # prints 6
And then in another file (main.py):
from my_lib import *
if __name__ == "__main__":
init()
print foo # prints 1 instead of 6!!
It prints 1 because it refers to the foo created with the import. The one that is 6 refers to sys.modules['my_lib'].frame_count
instead.
This is because I use the import *
.
But without I have to use my_lib.
as a prefix all the time.
And I can do import my_lib as l
to shorten that prefix but I don't want that.
So is there any way to make things global without this annoying side effect?
Answers
How interesting and somehow unexpected to me: >-)
And another curious fact: Java doesn't have actual global variables, but fields & methods. ~O)
However, when they're
public
, we have direct access to them. They're not clones as in Python. \m/But unfortunately, in order to access a
public
member of some class, we need to rely on the dot.
operator for it. Not as clean & direct as local variables though. :(However, there's a hackish way to make fields to behave as local variables in Java: :ar!
We declare them as
static
. And then import itsclass
w/import static
:Let's say we compile a
class
called MutableInt and use it as a library:MutableInt.java:
Now in Processing's IDE (PDE), we can directly access its field num as if it was a global variable like this:
GlobalVariable.pde:
Even though num has not been declared as a variable anywhere within the sketch, it behaves as such.
And for any other ".java" files which happen to
import static
field num as well, they're gonna get the actual num, w/ the most current modified value. In this case5
if it's executed after the sketch. :)>-__add__()
in order to overload the add+
operator for the class: *-:)http://ThePythonGuru.com/python-operator-overloading/
+
operator; then return self.+=
. $-)=
, even its composite+=
form, another Number object is created and reassigned to it. :-SS=
operator is performed. :-Bmy_lib.py:
Mutable_Global_Number.pyde:
Thanks a lot. I think I just go with extending a class with the things I need. I don't really like it but out of all the solutions with their drawbacks it's still the one I like the most.