Domanda

I was looking for a python analogous of (C)

 if ((p = malloc(N * sizeof(*p))) == NULL) return 1;

Something like user = getUser() or return does not work nor would if (user = getUser() is None) return - what's the pythonic way ?

È stato utile?

Soluzione

If you are looking for a way to assign and check the assigned value in one go, there isn't one, and Python dissuades you from creating one.

user = get_user()
if user is None:
    return None

Altri suggerimenti

You could use context management under two conditions:

  • The get_user() return a class type you can tweak

  • You are willing to define two special functions in the class returned by get_user, namely

    __enter__(self)
    __exit__(self, exception_type, exception_value, traceback)
    

Now, lets suppose your User class is all set and ready, then you could write the following

with get_user() as user:
    # do what you need to do 

So this way the assignment happened in the with statement which calls your special methods upon entering and exiting the context management scope. Inside those methods you can specify the checks and the behavior uppon failure or success to comply with your specifications

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top