Can you replace commands with variables in python?

2

I'm having a question, can I save commands in variables? For example: X = while X (True):

So I could facilitate some things in some scripts, or kind of try to "create" a proper language, I hope someone can help me! : -)

    
asked by anonymous 02.05.2018 / 04:50

2 answers

4

You can save functions:

def minha_funcao(x):
    while True:
        x += 1
        print(x)
        if x % 5 == 0:
            break

minha_variavel_func = minha_funcao
minha_variavel_func(2)  # Executa minha_funcao com 2 como argumento x

If it fits on a line, you can also use a lambda:

minha_lambda = lambda: print(*[i for i in range(4)])
minha_lambda()  # Printa "0 1 2 3"
    
02.05.2018 / 04:56
1

Apparently what you're trying to do is create a macro , a feature that Python does not have. You can try using macropy , a library that implements this, but it seems, in a very complicated way (requires manipulation of the Python syntax tree).

If you want to create a kind of Domain-Specific Language (DSL), it's easier. Python will have some limitations for this, but depending on how far you want to go, it also provides tools, from the use of lambdas and decorators, to metaclasses, module inspect, etc.

Another option is to look for a language that has the native macros feature, such as LISP or Elixir .

    
10.05.2018 / 00:00