yglukhov / nimpy

Nim - Python bridge
MIT License
1.48k stars 60 forks source link

Dunder methods #43

Closed erhlee-bird closed 6 years ago

erhlee-bird commented 6 years ago

The magic/dunder methods rely on identifiers with underscores incompatible with Nim identifiers. Below is an example of a common interaction with Python context managers where a slight workaround is needed to invoke such methods.

import macros

import nimpy

let None = pyBuiltins().None

template with_py(context: typed, name: untyped, body: untyped) =
  try:
    # Can't use the `.` template
    let name = callMethod(context, "__enter__")  # context.__enter__()
    body
  finally:
    discard callMethod(context, "__exit__", None, None, None)

let os = pyImport("os")

os.scandir(os.getcwd()).with_py(context):
  for entry in context:
    echo entry.name.to(string)

This works just fine, but it seems like this could be a spot for some convenience wrapper/convention for dealing with Python context managers. Any thoughts on anything nimpy might want to support?

alehander92 commented 6 years ago

I am surprised b.__enter__ doesn't work, maybe that would make sense to be supported by nim's quotes

Vindaar commented 6 years ago

So patching the lexer to allow underscored identifiers within accent quotes is pretty straight forward. See: https://github.com/Vindaar/Nim/commit/d047887b8844851d748e30ff7755243f555ac543 Makes your example work fine, if as @alehander42 suggested, __enter__ is put into backticks.

If promoting good Python interoperability is a goal of Nim, this would be nice to have I guess. I can see it opening a can of worms though, although all tests seem to pass on my machine. I'm pretty skeptical this would actually get merged though. :)

yglukhov commented 6 years ago

I'm pretty skeptical this would actually get merged though

There's only one way to find out :)

alehander92 commented 6 years ago

Please, PR it to Nim @Vindaar, I think it is useful

yglukhov commented 6 years ago

Ok, so the alternatives are:

  1. Keep the status quo. Since dunder methods are not used often, it's ok for them to look not pretty.
  2. Provide pretty aliases, with nim-friendlier names.

I'd go with 1 tbh, but I admit I'm not a day-to-day python user, so I might be missing smth.

yglukhov commented 6 years ago

Closing this since no objections. Feel free to bring more arguments though.

xyb commented 3 years ago

@yglukhov Hopefully we can reconsider this, because we can't define iter and next to implement a Python iterator without supporting the names of the magic methods.