On 2020-11-26 19:41, MRAB wrote:
On 2020-11-27 02:30, Ned Batchelder wrote:
On 11/26/20 9:02 PM, MRAB wrote:
On 2020-11-27 01:12, Ned Batchelder wrote:
On 11/26/20 6:44 AM, 3mi...@gmail.com wrote:
Add something like Move type hint to typing module. It will tell the
analyzer that the input parameter of the function is moved and can
not be used after. For example:
```
def f(d: Move[dict]) -> dict:
     d['a'] = 2
     return d

d = {1: 2}
f(d)
print(d[1])  # mistake, using of moved value

Maybe I'm behind the times on the latest thinking in programming
languages.  I'm not familiar with "move semantics". Can someone explain
what is wrong with the code above?  What is the mistake? `print(d[1])`
will work perfectly fine.  The function changes the 'a' key, and then we
access the 1 key. Should the example have used the same key in both
places?

d is moved into function f. f does return d when it exits, moving it
out back again, but as the caller doesn't bind to it, it's discarded.

It's not discarded, it's still referenced by d in the outer scope.

No, it's not any more, and that's the point. It was _moved_ into the
function, and although the function returned it, it was discarded
because the caller didn't bind it to keep hold of it.

This doesn't make sense as a description of the actual semantics of the Python code. The value isn't "moved", it is passed like all arguments, and the function mutates it, so the mutated dict IS accessible from the calling code. If we're talking about adding something to typing module that would make this raise an error in type checking, that's one thing, but (I hope) no one is suggesting that that would have any impact on what the code actually does. There's just (hypothetically) a type hint saying `d` "shouldn't" be used after the call. To say it "was moved" and "is not [referenced] any more" is incorrect. Those are just things that are type-hinted, not things that actually happen.

        If you have:

def f(x: int) -> str:
        x = "hello"
        return 3

f("goodbye")

. . .it's not correct to say that you "didn't" call f with a string value or that a new string value "wasn't" assigned or that an int "wasn't" returned. All of those things happened. They're a violation of the type hints, but those are just hints and what happens still happens. Type hints don't say anything about what happens, only what is "supposed" to happen.

--
Brendan Barnwell
"Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail."
   --author unknown
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DZZTK4OQRLNIQLICDOSX5HLPWSU2FVQW/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to