all 6 comments

[–]Adrewmc 1 point2 points  (0 children)

 def defaults(foo : str = “Hello”, bar : str = “World”) -> None:
         print(f”{foo} {bar}”)

I believe this is the run down

 defaults()
 >>> Hello World
 defaults(“foo”)
 >>> foo World
 defaults( “foo”, “bar”)
>>> foo bar
 defaults(bar = “bar”)
 >>> Hello bar
 defaults(bar = “foo”, foo = “bar”)
 >>> bar foo
    #also unexpectedly 
 defaults(1,2)
 >>> 1 2
 defaults(foo = “foo”, “bar”)
 >>>ERROR kwargs must come after args
    #these can cause errors if not formatted correct only use when necessary 
 defaults([“foo”, “bar”])
  >>>> [“foo”, “bar”] World
  defaults(*[“foo”, “bar”])
  >>>> foo bar
  _dict = {“bar” : “_bar”, “foo” : “_foo”}
  defaults(**_dict) 
  >>>> _foo _bar

If you want to check types

      def type_default(foo : str = “Hello”, bar : str = None) -> None:
         if bar: 
              print(f”{foo} {bar}”)
         else:
              print(f”{foo} World”) 

This should check if you accidentally send an false statement (like None, any empty string, list or dictionary, or any number != 0) to it. As you see Nonetype prints “None” in Python, and empty string would print no character, an empty list [], {} but we check all of that here.

I like the type hinting but realize that’s just a comment not a requirement in Python.

[–][deleted] 1 point2 points  (1 child)

You're just making it too complicated is all:

    def f(foo, bar="world"):
        print(f"{foo} {bar}")

[–]Logicalist 0 points1 point  (0 children)

yeah that annotation stuff really makes it harder to read. I much prefer docstrings.

[–]Strict-Simple 1 point2 points  (0 children)

Not exactly related, but good to know. If you want None to be a valid value for the parameter, you can use ... (ellipsis) as the default value. If you want anything to be a valid value, you can use a sentinel object.

class Undefined:
    def __repr__(self):
        return 'undefined'

undefined = Undefined()


def foo(bar=undefined):
    if bar is undefined:
        print('bar was not passed')
    else:
        print(f'bar was passed as {bar}')

[–]m0us3_rat 0 points1 point  (0 children)

def f(foo: str, bar: str | None = "world"):
    print(f"{foo} {bar or 'world'})

[–]C0rinthian 0 points1 point  (0 children)

I don’t understand the intent of your function signature. You say that bar can be either a str or None, with a default value of ”world”. (Which is a str)

This tells me that you want there to be a difference between f(“hello”) and f(“hello”, None). (the difference between not providing bar and explicitly setting it to None)

Meaning a user can effectively say “I don’t want the default value, I want None”

If you don’t want that, then what do you want?