Skip to content

Implement getattr builtin function#65

Open
friendlymatthew wants to merge 1 commit intomainfrom
get_attr
Open

Implement getattr builtin function#65
friendlymatthew wants to merge 1 commit intomainfrom
get_attr

Conversation

@friendlymatthew
Copy link
Member

This PR adds the getattr(object, name[, default]) builtin function. For a given object, it returns the attribute value if it exists, the provided default value if the attribute doesn't exist and a default is given, or raises AttributeError otherwise

@codspeed-hq
Copy link

codspeed-hq bot commented Jan 23, 2026

Merging this PR will not alter performance

✅ 11 untouched benchmarks


Comparing get_attr (74cf03b) with main (7909646)

Open in CodSpeed

Comment on lines +30 to +52
let (mut positional, kwargs) = args.into_parts();

let pos_count = positional.len();
let kw_count = kwargs.len();

// Check for unsupported kwargs
if !kwargs.is_empty() {
for (k, v) in kwargs {
k.drop_with_heap(heap);
v.drop_with_heap(heap);
}
for v in positional {
v.drop_with_heap(heap);
}
return Err(ExcType::type_error_arg_count("getattr", 2, pos_count + kw_count));
}

if !(2..=3).contains(&pos_count) {
for v in positional {
v.drop_with_heap(heap);
}
return Err(ExcType::type_error_arg_count("getattr", 2, pos_count));
}
Copy link
Member

Choose a reason for hiding this comment

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

if we don't already have it, we should have and use a method on ArgValues to get 2 or 3 args, and use that.

Copy link
Member

Choose a reason for hiding this comment

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

you need gets for getting from a module.

Comment on lines +38 to +48
try:
getattr(s, 123)
assert False, 'getattr() with non-string name should raise TypeError'
except TypeError as e:
assert 'attribute name must be string' in str(e), 'Error message should mention string requirement'

try:
getattr(s, None)
assert False, 'getattr() with None name should raise TypeError'
except TypeError:
pass
Copy link
Member

Choose a reason for hiding this comment

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

always do an exact check on the message from TypeError

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.

2 participants