简体   繁体   中英

Working with python dictionary and Lambda functions

This is my code to write a simple qr code generator with options. How do I run the send function only when the correct option is chosen? I'm not calling the send function unless it is called when assigned? If so, how can I get the dictionary to contain the value I need but not call it?

// imports

import sys
import os
import requests
from PIL import Image
from io import BytesIO

// api-endpoint
URL = "https://api.qrserver.com/v1/create-qr-code"
data = "Example Text"
size = "200x200"
color = "0-0-0"  # black
bgcolor = "255-255-255"  # white

# defining a params dict for the parameters to be sent to the API
PARAMS = {'data': data, 'size': size, 'color': color, 'bgcolor': bgcolor}

check = False
while(not check):
    print("Welcome to my QR code generator")
    print("--------------------------------")
    print("Press 1 to add data (Default: \"Example Text\"")
    print("Press 2 to change size (Default: 200x200)")
    print("press 3 to change color (Default: 0-0-0 <-- Black)")
    print("Press 4 to change background color (Default: 255-255-255 <-- White)")
    print("Press 5 to show your selected options")
    print("Press c to create QR code")
    print("Press q to exit")


def Send(x):
    # sending get request and saving the response as response object
    r = requests.get(url=URL, params=x)
    r.content
    i = Image.open(BytesIO(r.content))
    i.show()
def CleanupAndQuit():
    exit()

menuchoices = {'1': AddData, '2': ChangeSize, '3': ChangeColor,
               '4': ChangeBGColor, '5': ShowAll, 'c': Send(PARAMS), 'q': CleanupAndQuit}
ret = menuchoices[input()]()
if ret is None:
    print("Please enter a choice")

In the definition of menuchoices you are immediately calling the function Send with PARAMS .

What you might try instead is using lambda expression :

menuchoices = {
   'c': lambda: Send(PARAMS)
}

This way you avoid immediate call to Send and keep it configured for lazy evaluation.

menuchoices字典中,您正在调用函数 Send。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM