ok, I'm sure the answer to this is very simple.. there may even be some component in the os package to do this... I want to do what the code underneath seems like it would do.. I understand it does not, and when I try to run the code, I get an error saying that variable is not a class or w.e.. but I want to run the function whose name is given by 'variable'. Is there like os.execute(variable) or something obvious like that? or maybe in the testF function, I add func = class(testF) or something similar.. I gotta know..

variable = 'testF'

def testF():
   print('Hello World!')

def reflect(what):
  what()

def main()
  reflect(variable)


main()

Edited 5 Years Ago by FALL3N: n/a

variable = 'testF'

def testF():
   print('Hello World!')

def reflect(what):
  globals()[what]()

def main():
  reflect(variable)


main()

I did not get any error message like you said however, only complaint of trying to use string as variable after fixing the missing :, usually we however do not use string to pass, but function as parameter:

def testF():
   print('Hello World!')

def greeting():
    print('Bravo!')

for variable in (testF, greeting):
    variable()

If you want to do indirect:

def testF():
   print('Hello World!')

def greeting():
    print('Bravo!')

def dothis(f):
    f()
    
for variable in (testF, greeting):
    dothis(variable)

Check also document I link here to easy your mind changing gears to Python: http://www.daniweb.com/software-development/python/threads/293127

Edited 5 Years Ago by pyTony: n/a

In python a 'variable' is usually called a 'name'. Each name belongs to a certain 'namespace' which is a python dictionary. Here, your statement def testF(): ... inserts the name "testF" in the global namespace, which is accessible by calling globals() . So your reflect function could be written

def reflect(functionname):
    function = globals()[functionname]
    return function()

edit: oops, tony was faster :)

Edited 5 Years Ago by Gribouillis: n/a

oh, ok, thank you very much tony and Grib, I think I get it.. but one question, in:

function = globals()[functionname]

and

globals()[what]()

is 'globals()' a namespace? and does a namespace work like a dictionary in the sense that you can add a key to a dictionary just by:

dictionary1['itemToAdd']

except this would be like dictionary1()

AND if that's the case, then would the comparison: functions are to namespaces, as keys are to dictionaries?

Edited 5 Years Ago by FALL3N: n/a

is 'globals()' a namespace? and does a namespace work like a dictionary in the sense that you can add a key to a dictionary just by:

Yes globals() are a namespace.
A namespace is it`s just like dictionary.

*** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. ***
>>> a = 5
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'a': 5,
 'pyscripter': <module 'pyscripter' (built-in)>}
>>> globals()['a']
5
>>> globals()['b'] = 6 #same as b = 6
>>> b
6
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'a': 5,
 'b': 6,
 'pyscripter': <module 'pyscripter' (built-in)>}
>>>

Python has 3 namespaces global namespace, local namespace, built-in namespace .
We can take a look at local namespace.

>>> def foo():
...     x = 'i am local'
...     return x
... 
>>> foo()
'i am local'
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'foo': <function foo at 0x01EE5AF0>,
 'pyscripter': <module 'pyscripter' (built-in)>}

>>> x #if we try to access x
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'x' is not defined

>>> #x are local to fuction foo
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'foo': <function foo at 0x01EE5AF0>,
 'pyscripter': <module 'pyscripter' (built-in)>}

>>> def foo():
...     global x #make x global
...     x = 'i am no longer only local'
...     return x
... 
>>> foo()
'i am no longer only local'

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 '__package__': None,
 'foo': <function foo at 0x01EE59F0>,
 'pyscripter': <module 'pyscripter' (built-in)>,
 'x': 'i am no longer only local'}

>>> x #x is now in global namspace
'i am no longer only local'

Using global x in function is foo() is ofen a bad way to program.
We are Pollution global namespace and can make debugging very hard.

oo, huh, thats interesting, I am pretty sure I understand it.. at least basically. But if globals() is just one of the three default namespaces (locals() and builtins() being the other two) back to my initial question: if we execute a function as a variable, such as was suggested in:

globals()[variable]

and not using

locals()[variable]

or

builtins()[variable]

are all user declared functions automatically added by the compiler to the globals() namespace?

oo, huh, thats interesting, I am pretty sure I understand it.. at least basically. But if globals() is just one of the three default namespaces (locals() and builtins() being the other two) back to my initial question: if we execute a function as a variable, such as was suggested in:

globals()[variable]

and not using

locals()[variable]

or

builtins()[variable]

are all user declared functions automatically added by the compiler to the globals() namespace?

No, functions defined at top level in the main program or a module are automatically added to the global namespace of that module (each module, like most class instances, have a member __dict__ which is a dictionary). Functions defined in the body of a class definition are added to the classe's __dict__.

The concept of global namespace, or local namespace is rather a dynamic concept. When the program executes, whenever the cursor is, there is a local namespace and a global name space. For example

# this is the source file of a module XXX

def the_ultimate_function():
    x = 1
    print "hello" # <---- suppose that we are currently executing this statement

When 'print "hello"' is executed, the global namespace is the dictionary __dict__ of the current module XXX (which contains for example a key 'the_ultimate_function') and the local namespace is a dictionary created when the function's execution starts. This dictionary currently contains { 'x': 1 }.

When you call globals() or locals(), python returns the current global and local dictionaries.

oooooo, so if I wanted to define a namespace, would make a folder with the same name as the namespace with a text file inside called __dict__, containing:

'example' :'/path/to/a/file/called/example.py',
'example2', :''/path/to/a/file/called/example2.py'
'example3', :''/path/to/a/file/called/example3.py'

where 'example2.py' contains your 'the_ultimate_function()'

and then use that function, and variables in the namespace by saying:

from example import *

and then add that original folder to my PATH or PYTHONPATH?

oooooo, so if I wanted to define a namespace, would make a folder with the same name as the namespace with a text file inside called __dict__, containing:

'example' :'/path/to/a/file/called/example.py',
'example2', :''/path/to/a/file/called/example2.py'
'example3', :''/path/to/a/file/called/example3.py'

where 'example2.py' contains your 'the_ultimate_function()'

and then use that function, and variables in the namespace by saying:

from example import *

and then add that original folder to my PATH or PYTHONPATH?

No, no, not at all. You don't need to define namespaces, and python defines __dict__ for you. If you want to use modules and imports, read this http://docs.python.org/py3k/tutorial/modules.html

oooooo, so if I wanted to define a namespace, would make a folder with the same name as the namespace with a text file inside called __dict__, containing:

We are now talking about inner working og namespaces.
Python add to namespace auto and dont write strange code that use namespaces in a wrong way.
Writing code like this should be avoided almost always.

globals()[what]() | function = globals()[functionname] | globals()['b'] = 6 #same as b = 6

The Zen of Python.
http://www.python.org/dev/peps/pep-0020/

Edited 5 Years Ago by snippsat: n/a

oh ok, thanks.. I thought it meant we had to define the namespace by creating a folder with some py or txt file giving paths and definitions to package contents, as well as other files for the local() and globals() dictionaries...

I see that creating a package to import is a different question, so getting away from that, why do these dictionaries and other system variables start with '__' and end with '__'? And, also, I think I saw somewhere a '__main__'.. can I write a __main__ that will act like the main function? (the defalut function the system runs first)

similar to: '

public static void main(String[] Args)

in java?

All calls of module is run at run time. Main use of __main__ you see is to recognize the case of running of module as program from case it is imported to other modules and is not supposed to run anything. You can set some global dictionaries, initialize the main objects (like tkinter to run Gui engine) and typically call major code which you can name main if you do not find moredescriptive name.

The __ at begining and end means you do not want variable used from other modules or for 'magick methods' name, like __init__ method in classes.

The idiom for main program lines is if statement:

if __name__ == '__main__':
       # my code here

oh ok, but theres no way (without tkinter or some other GUI engine) to have a 'main' ir 'init' method, that runs automatically on initialization?

This question has already been answered. Start a new discussion instead.