python not accept keyword arguments

前端 未结 5 1091
萌比男神i
萌比男神i 2021-01-12 08:13

I am trying to make my code NOT to accept keyword arguments just like some bulitins also do not accept keyword arguments, but, I am unable to do so. Here, is my thinking acc

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 08:27

    I think this is a very bad Python feature, and can lead to very unmaintainable and buggy code. Suppose you had a function:

    def myurl(x, y):
        url = "{}:{}".format(x, y)
        return url
    

    Although it might look like a good idea to enable replacing positional with keyword arguments don't ever do that. I'm surprised that there is no Python option that would prevent this function to be called with keyword arguments:

    >> print myurl(x="localhost", y=8080)
    

    If someone figures out the library would be more readable if written as:

    def myurl(hostname, port):
        url = "{}:{}".format(hostname, port)
        return url
    

    then the rest of the code that used keyword calling as myurl(x="localhost", y=8080) would fail:

    TypeError: myurl() got an unexpected keyword argument 'x'
    

    This means that your local function variable all of the sudden became a global variable! I was hoping this issue would be somehow addressed in Python 3.

提交回复
热议问题