MCPcopy Index your code
hub / github.com/datacamp/pythonwhat / check_keys

Function check_keys

pythonwhat/checks/check_object.py:303–372  ·  view source on GitHub ↗

Check whether an object (dict, DataFrame, etc) has a key. ``check_keys()`` can currently only be used when chained from ``check_object()``, the function that is used to 'zoom in' on the object of interest. Args: key (str): Name of the key that the object should have. mi

(state, key, missing_msg=None, expand_msg=None)

Source from the content-addressed store, hash-verified

301
302
303def check_keys(state, key, missing_msg=None, expand_msg=None):
304 """Check whether an object (dict, DataFrame, etc) has a key.
305
306 ``check_keys()`` can currently only be used when chained from ``check_object()``, the function that is
307 used to 'zoom in' on the object of interest.
308
309 Args:
310 key (str): Name of the key that the object should have.
311 missing_msg (str): When specified, this overrides the automatically generated
312 message in case the key does not exist.
313 expand_msg (str): If specified, this overrides any messages that are prepended by previous SCT chains.
314 state (State): The state that is passed in through the SCT chain (don't specify this).
315
316 :Example:
317
318 Student code and solution code::
319
320 x = {'a': 2}
321
322 SCT::
323
324 # Verify that x contains a key a
325 Ex().check_object('x').check_keys('a')
326
327 # Verify that x contains a key a and a is correct.
328 Ex().check_object('x').check_keys('a').has_equal_value()
329
330 """
331
332 state.assert_is(["object_assignments"], "is_instance", ["check_object", "check_df"])
333
334 if missing_msg is None:
335 missing_msg = "There is no {{ 'column' if 'DataFrame' in parent.typestr else 'key' }} `'{{key}}'`."
336 if expand_msg is None:
337 expand_msg = "Did you correctly set the {{ 'column' if 'DataFrame' in parent.typestr else 'key' }} `'{{key}}'`? "
338
339 sol_name = state.solution_parts.get("name")
340 stu_name = state.student_parts.get("name")
341
342 if not isDefinedCollInProcess(sol_name, key, state.solution_process):
343 raise InstructorError.from_message(
344 "`check_keys()` couldn't find key `%s` in object `%s` in the solution process."
345 % (key, sol_name)
346 )
347
348 # check if key available
349 state.do_test(
350 DefinedCollProcessTest(
351 stu_name, key, state.student_process, FeedbackComponent(missing_msg, {"key": key})
352 )
353 )
354
355 def get_part(name, key, highlight):
356 if isinstance(key, str):
357 slice_val = ast.Constant(value=key)
358 else:
359 slice_val = ast.parse(str(key)).body[0].value
360 expr = ast.Subscript(

Callers 1

test_data_frameFunction · 0.90

Calls 5

isDefinedCollInProcessFunction · 0.90
part_to_childFunction · 0.90
get_partFunction · 0.85
assert_isMethod · 0.80

Tested by 1

test_data_frameFunction · 0.72