0llie_C
0llie_C

Reputation: 17

When calling a function from a module can you say what is returned? (Python)

It may sound a bit noobish but say i call a function from the module psutils, is there a way to say which value i want back

for example:

    psutil.swap_memory()

returns

    swap(total=A, used=B, free=C, percent=D, sin=0, sout=0)

is there a way to make it only return B and C?

Upvotes: 0

Views: 49

Answers (2)

fuesika
fuesika

Reputation: 3330

Based on dm03514's posting, I suggest you use a customized wrapper for swap_memory():

def my_swap_memory():
    _, used, free, _, _, _ = psutil.swap_memory()
    return swap(B=used, C=free)

and then call it like

returndata = my_swap_memory()

Upvotes: 0

Blender
Blender

Reputation: 298432

There are a few ways, the most obvious being:

info = psutil.swap_memory()
used, free = info.used, info.free

The returned object is actually a tuple-like object, so you could also slice it and then unpack it:

used, free = psutil.swap_memory()[1:3]

There's also the more convoluted approach, which has the advantage of ignoring order:

from operator import attgetter

used, free = attrgetter('used', 'free')(psutil.swap_memory())

Upvotes: 2

Related Questions