0

Assume for example that I am writing a function for the following code (in pandas module):

myData.sort_values(by=myVariable, ascending=False)

Now, I want to create a function whose variables are data, variable and ascending.

sort(data=mydata, variable=myvariable, ascending=False)

The below function gives an error, because whether ascending is true or false is not given in second line:

def sort(data,variable,ascending=False):
    data.sort_values(by=variable, ascending)

Although it would work, I do not want to change variable name such as:

def sort(data,variable,asc=False):
    data.sort_values(by=variable, ascending=asc)

One last approach would be to create a variable inside the function:

def sort(data,variable,ascending=False):
    asc = ascending
    data.sort_values(by=variable, ascending=asc)

but it looks somewhat confusing. Is there an alternative approach to use the same variable in this case?

Note: the question is not related with pandas module, it is just an example.

Edit: I have clearly stated my problem and showed what I have tried. I did not understand the reason for the downvote.

ThePortakal
  • 229
  • 2
  • 10
  • There are functions in python that can take positional arguments and keyword only arguments. If there is such a keyword only constraint set on the arguments, you can't call it as positional arguments. Have a look at [this question](https://stackoverflow.com/questions/54252179/how-to-create-a-python-function-which-take-only-positional-arguments-and-no-keyw). – Diptangsu Goswami Oct 19 '19 at 08:32

2 Answers2

3

have you tried:

def sort(data,variable,ascending=False):
    data.sort_values(by=variable, ascending=ascending)
Nick Martin
  • 731
  • 3
  • 17
0

The below function gives an error, because whether ascending is true or false is not given in second line:

def sort(data,variable,ascending=False):
    data.sort_values(by=variable, ascending)

No; it gives an error because positional arguments cannot come after keyword arguments. Like the error message says: SyntaxError: positional argument follows keyword argument.

The way to fix this is as in the other answer, using ascending=ascending. The idea is that the arguments for the function call are in a separate namespace from the current local variables.

If it "didn't work", then you need to ask a new question and properly explain the expected and actual results, with a complete example that other users can test locally.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153