Pak
Pak

Reputation: 736

Using the return value of a function as the value in a dictionary in python

I'm creating a python application that requires a user to log into a web service. The credentials are passed to the server in a POST request as a json dictionary. In order to avoid unnecessarily saving the password in a variable I figured I would do something like the following:

json.dumps({'username': raw_input('Username: '), 'password': getpass.getpass()})

  1. Is there any guarantee that raw_input will get called before getpass?
  2. Is there actually any benefit in this method over saving the output of the functions first and then creating the dictionary from the variables?
  3. Is this a 'pythonic' way of doing things? My guess is no since there is a lot of stuff crammed into a single line and it's arguably not very readable.

Upvotes: 0

Views: 88

Answers (2)

lqhcpsgbl
lqhcpsgbl

Reputation: 3782

If you want to insure raw_input() called before getpass(), I think you should use variables like this:

username = raw_input('Username: ')
passwd = getpass.getpass()

user_dict = {username : passwd}

Use variable will make your code more readable and easy to maintenance or debug.

First, the code will be execute as raw_input('Username: ') then getpass.getpass() make a dict at last.

Second, it's more shorter and if your program is small and easy that's a good way .

Third, it's short, kind of pythonic I guess but not good in engineering side.

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113948

  1. yes , since python is evaluated left to right like english. the functions will be called left to right.
  2. its slightly shorter
  3. not super pythonic but not aweful either

Upvotes: 3

Related Questions