Python: Using one argument to handle choice between a number and a string?

tangleduniform8

Basically I am writing a function that depends on a numerical input x, a number between 0 and 1. I want the default value of x to be, say, x=0.5. However, I also want to provide an option to the user that allows them to let the program select x for them using some algorithm. Is there an elegant way to handle that choice with one function argument?

I'm thinking something like this:

def foo(x=0.5):
    if x == "pick for me":
        return complicated_algorithm_that_picks_x()
    else:
        return x

def complicated_algorithm_that_picks_x():
    print "Thinking hard..."
    return 0.1234567

which would return:

>>> foo()
0.5
>>> foo(0.3)
0.3
>>> foo("pick for me")
Thinking hard...
0.1234567

But this looks really inelegant, since the user has to know what magic string to pass to invoke the selection algorithm. Any ideas how I can handle this more cleanly?

I was thinking having an additional Boolean argument called pick (that defaults to False), which when True will invoke the x picking function. But then users might pass both, say, x=0.3 and pass=True, in which case I have to arbitrarily ignore one of the choices. Looks clumsy again.

jme

There are three things you might consider:

  1. Split the one function into two.
  2. Use a class.
  3. Multiple default arguments.

Here there are, in no particular order:

Split one function into two

If you want to do two different things in one function and you're having trouble designing a natural interface, it might be a sign that the one function should become two:

def foo_picked_for_me():
    x = pick_x()
    return foo(x)

def foo(x):
    # do foo
    pass

I don't know how this strikes you, but it's simple, clear, and that means its often preferable.

Use a class

Default arguments are nice, but a function's interface can only get so complicated before it starts making more sense to handle option setting with a class:

class Foo:

    def __init__(self):
        self.x = 0.5

    def pick_x_for_me(self):
        self.x = pick_x()

    def foo(self):
        # do foo with self.x

As EOL suggests below, it's perfectly pythonic to leave x "exposed", and to allow the user to change it. You say, though, that x must be between 0 and 1, so it might make sense to do some bounds checking with the setter for x:

class Foo(object):

    def __init__(self):
        self._x = 0.5

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        if 0 <= value <= 1:
            self._x = value
        else:
            raise ValueError("x must be between 0 and 1")

    def pick_x_for_me(self):
        self._x = pick_x()

    def foo(self):
        pass
        # do foo with self._x

Multiple default arguments

The last option is analogous to what other posters have given: use two arguments, and throw an exception if the user does something contradictory. I'd consider allowing three forms of call:

    # x gets its default value of 0.5
    foo()

    # x gets the specified value
    foo(x=.42)

    # x is picked for me
    foo(pick_for_me=True)

Additionally, if I write:

foo(x=.42, pick_for_me=True)

I'll throw an exception. Some code that implements this follows:

def foo(x=None, pick_for_me=None):
    if x is None and pick_for_me is None:
        x = 0.5
    elif pick_for_me and x:
        raise RuntimeError("You can't set both!")
    elif pick_for_me:
        x = picking_algorithm()

    # else x was set, so leave it be

This is kind of complicated, and I'm not so sure I like the API. Just make sure you document the behavior well enough so that the user knows how to use the thing.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Python: Using one argument to handle choice between a number and a string?

From Dev

Python making a string a choice?

From Dev

How to remove spaces between a string and an argument when using the print statement in Python?

From Dev

Using enum class to handle user choice (polymorphic)

From Dev

How to Split a string onto an array using "," but string(s) may be of more then one length/number of delimiters? (Python 2.7)

From Dev

get number between two string by using substring

From Dev

How have a variable number of parameters for one argument in Python with argparse?

From Dev

python-argparse: assign a choice to each argument

From Dev

Python Pandas: Using a map function within a lambda / TypeError: ("int() argument must be a string, a bytes-like object or a number, not 'list'"

From Dev

int() argument must be a string or a number, not 'builtin_function_or_method' - python

From Dev

TypeError: float() argument must be a string or a number, not 'list' python

From Dev

Among several given ways to test a string against two possible values using strcmp, is one of them an obvious choice?

From Dev

How to give one space between number in json string java?

From Dev

How to give one space between number in json string java?

From Dev

Handle Large number in Python

From Dev

Differentiate string and number argument in perl

From Dev

int() argument must be a string or a number

From Dev

Extract Number before a Character in a String Using Python

From Dev

Replacing string+number in a file using Python

From Dev

Truncating a number using string find method in Python

From Dev

concatenate the argument of date into one string

From Dev

Validate if input string is a number between 0-255 using regex

From Dev

How to pass string as command line argument in python using C#

From Dev

How to pass string as command line argument in python using C#

From Dev

Print out text using one String in Python

From Dev

difference between character array initialized with string literal and one using strcpy

From Dev

difference between character array initialized with string literal and one using strcpy

From Dev

How to find the number of strings between strings in a file/string - python

From Dev

Using _.partial on function with one argument

Related Related

  1. 1

    Python: Using one argument to handle choice between a number and a string?

  2. 2

    Python making a string a choice?

  3. 3

    How to remove spaces between a string and an argument when using the print statement in Python?

  4. 4

    Using enum class to handle user choice (polymorphic)

  5. 5

    How to Split a string onto an array using "," but string(s) may be of more then one length/number of delimiters? (Python 2.7)

  6. 6

    get number between two string by using substring

  7. 7

    How have a variable number of parameters for one argument in Python with argparse?

  8. 8

    python-argparse: assign a choice to each argument

  9. 9

    Python Pandas: Using a map function within a lambda / TypeError: ("int() argument must be a string, a bytes-like object or a number, not 'list'"

  10. 10

    int() argument must be a string or a number, not 'builtin_function_or_method' - python

  11. 11

    TypeError: float() argument must be a string or a number, not 'list' python

  12. 12

    Among several given ways to test a string against two possible values using strcmp, is one of them an obvious choice?

  13. 13

    How to give one space between number in json string java?

  14. 14

    How to give one space between number in json string java?

  15. 15

    Handle Large number in Python

  16. 16

    Differentiate string and number argument in perl

  17. 17

    int() argument must be a string or a number

  18. 18

    Extract Number before a Character in a String Using Python

  19. 19

    Replacing string+number in a file using Python

  20. 20

    Truncating a number using string find method in Python

  21. 21

    concatenate the argument of date into one string

  22. 22

    Validate if input string is a number between 0-255 using regex

  23. 23

    How to pass string as command line argument in python using C#

  24. 24

    How to pass string as command line argument in python using C#

  25. 25

    Print out text using one String in Python

  26. 26

    difference between character array initialized with string literal and one using strcpy

  27. 27

    difference between character array initialized with string literal and one using strcpy

  28. 28

    How to find the number of strings between strings in a file/string - python

  29. 29

    Using _.partial on function with one argument

HotTag

Archive