0

The following code to generate a quick plot of some data works fine when I run it in the cell within my notebook:

def xyz_plot(df=df, sensor='acc', position='t', activity='walking_treadmill_flat', 
        person=np.random.randint(1,9)):
        sensors = [f'{position}_{i}{sensor}' for i in ['x','y','z']]
        subset = df.query(f"person=='{person}' & activity=='{activity}'")
        for j in sensors:
            sns.lineplot(subset.seconds[100:200], subset[f'{j}'][100:200], label=f'{j}', legend='full').set(xlabel='', ylabel='Seconds',                                                      title=f'Person:{person}')
    

However, when I save it in my_functions.py file which I have imported as follows it no longer works and cannot find my data frame. How can I fix this?

from my_functions import xyz_plot
Mitchell van Zuylen
  • 3,905
  • 4
  • 27
  • 64

1 Answers1

0

When you call your function, pass the argument to it, rather than setting it as a default argument!

If you must have default arguments, make sure they're not mutable

function declaration

def myfunction(arg, arg2=None):
    work_with_arg(arg)

function call

from mylibrary import myfunction

...
myfunction(dataframe)  # arg refers to the dataframe in the function

This structure should also be used to prevent problems with your person argument (see note about mutable default args), as the random value will be calculated only once on import / function declaration (which may be desired, but probably isn't..)

>>> import numpy as np
>>> def broken(x=np.random.randint(1,9)):
...     print(x)
...
>>> broken()
7
>>> broken()
7
>>> broken()
7
>>> broken()
7

more proper

>>> def happy(x=None):
...     if x is None:
...         x=np.random.randint(1,9)
...     print(x)
...
>>> happy()
4
>>> happy()
7
ti7
  • 16,375
  • 6
  • 40
  • 68