Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional Arguments #86

Merged
merged 17 commits into from Apr 16, 2021
Merged

Optional Arguments #86

merged 17 commits into from Apr 16, 2021

Conversation

gchenfc
Copy link
Member

@gchenfc gchenfc commented Apr 8, 2021

This PR is a first-pass approach at optional arguments. It can recognize expressions such as:

void func(int a = 2);
void func2(gtsam::KeyFormatter kf = gtsam::DefaultKeyFormatter);

in the interface file, and converts them with the appropriate pybind notation

This should make wrapping GTdynamics with the correct keyformatters a little nicer.
Although it is true that this could be done just as well with overloading and defining appropriate optional arguments in C++, implementing these optional arguments isn't too much code and should make code a little cleaner.

gtwrap/interface_parser/tokens.py Outdated Show resolved Hide resolved
gtwrap/interface_parser/tokens.py Outdated Show resolved Hide resolved
gtwrap/interface_parser/tokens.py Outdated Show resolved Hide resolved
@varunagrawal
Copy link
Collaborator

Did some refactoring to reduce duplication and use more of pyparsing superpowers. @gchenfc check it out when you get a chance. 🙂

@varunagrawal
Copy link
Collaborator

Adding @ProfFan as a reviewer since I contributed code. @ProfFan this is a big PR so please take your time with this and try to catch as many issues as possible.

Copy link
Collaborator

@ProfFan ProfFan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general it looks great. I'll do another review round after the fixes :)

rule = ((Type.rule ^ TemplatedType.rule)("ctype") +
IDENT("name")).setParseAction(lambda t: Argument(t.ctype, t.name))
rule = ((Type.rule ^ TemplatedType.rule)("ctype") + IDENT("name") +
Optional(EQUAL + (DEFAULT_ARG ^ Type.rule ^ TemplatedType.rule) +
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe in unit test point out which test corresponds to which rule (DEFAULT_ARG, type, templated).

self.default = tuple(default.asList())
else:
# An empty string
self.default = default
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not "" if it's really empty?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe make this a type

# Encapsulating type for numbers, and single and double quoted strings.
# The pyparsing_common utilities ensure correct coversion to the corresponding type.
# E.g. pyparsing_common.number will convert 3.1415 to a float type.
_type = (pyparsing_common.number ^ QuotedString('"') ^ QuotedString("'"))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_type is not a great name. Maybe NUMBER_OR_QUOTED_STRING?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renaming it to NUMBER_OR_STRING.

py_args = []
for arg in args_list.args_list:
if arg.default and isinstance(arg.default, str):
arg.default = f"\"{arg.default}\""
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think f-strings are post 3.8.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah good catch!

if method.name == 'print':
# Redirect stdout - see pybind docs for why this is a good idea:
# https://pybind11.readthedocs.io/en/stable/advanced/pycpp/utilities.html#capturing-standard-output-from-ostream
ret = ret.replace('self->', 'py::scoped_ostream_redirect output; self->')
ret = ret.replace('self->print', 'py::scoped_ostream_redirect output; self->print')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you have this

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite understand your comment.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nvm saw the next comment

[](const {cpp_class} &a) {{
# Make __repr__() call print() internally
ret += '''{prefix}.def("__repr__",
[](const {cpp_class}& self{opt_comma}{args_signature_with_names}){{
gtsam::RedirectCout redirect;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

then why do we still want this?

Copy link
Member Author

@gchenfc gchenfc Apr 9, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

print_ prints to (python) stdout whereas __repr__ returns a string. We could have print_ be like py::print(__repr__(self)) or something but I don't see a huge advantage to doing that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I mean if we use py::scoped_ostream_redirect then we don't need to use the GTSAM redirect anymore.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should tackle this in another PR so that we don't inadvertently break something. 😕

function varargout = print(this, varargin)
% PRINT usage: print(string s, KeyFormatter keyFormatter) : returns void
% Doxygen can be found at https://gtsam.org/doxygen/
if length(varargin) == 2 && isa(varargin{1},'char') && isa(varargin{2},'gtsam.KeyFormatter')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's interesting that the print method is here. I think by default it should use obj.display, but maybe that does not support custom KeyFormatter.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not even touching the Matlab code right now because I am not the right person to do that.

IDENT("name")).setParseAction(lambda t: Argument(t.ctype, t.name))
rule = ((Type.rule ^ TemplatedType.rule)("ctype") + IDENT("name") +
Optional(EQUAL + (DEFAULT_ARG ^ Type.rule ^ TemplatedType.rule) +
Optional(LPAREN + RPAREN))("default")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this optional used anywhere?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it is. It is required to parse default constructors, e.g. = NonlinearFactorGraph() since Type will only parse NonlinearFactorGraph.

Added a comment.

rule = ((Type.rule ^ TemplatedType.rule)("ctype") +
IDENT("name")).setParseAction(lambda t: Argument(t.ctype, t.name))
rule = ((Type.rule ^ TemplatedType.rule)("ctype") + IDENT("name") +
Optional(EQUAL + (DEFAULT_ARG ^ Type.rule ^ TemplatedType.rule) +
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this maybe be

Optional( EQUAL +
  (DEFAULT_ARG ^
    ( (Type.rule ^ TemplatedType.rule) + Optional(LPAREN + RPAREN) )
  )
)

???

i.e. It can either be a default arg, or a constructor?

Also maybe Optional(LPAREN + DEFAULT_ARG + RPAREN) ? so that the constructor can take constant arguments?

Actually there could even be nested constructors... oh jeez this is getting really involved

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rule handles the left and right parens properly, check out the tests. I've added a check where if it is a Type, then to add back the parens.

My design sense says not to support non-default constructors. If the user wanted non-default constructors, then why use a default argument in the first place?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That being said, maybe we can replace Type/TemplatedType with a Constructor rule?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the constructor rule supports templating*

Copy link
Collaborator

@ProfFan ProfFan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A great leap for mankind

@varunagrawal varunagrawal merged commit 015b12d into master Apr 16, 2021
@varunagrawal varunagrawal deleted the feature/optionalargs branch April 16, 2021 02:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants