Checks whether student imported a package or function correctly. Python features many ways to import packages. All of these different methods revolve around the ``import``, ``from`` and ``as`` keywords. ``has_import()`` provides a robust way to check whether a student correctly imported
(
state,
name,
same_as=False,
not_imported_msg="Did you import `{{pkg}}`?",
incorrect_as_msg="Did you import `{{pkg}}` as `{{alias}}`?",
)
| 493 | |
| 494 | |
| 495 | def has_import( |
| 496 | state, |
| 497 | name, |
| 498 | same_as=False, |
| 499 | not_imported_msg="Did you import `{{pkg}}`?", |
| 500 | incorrect_as_msg="Did you import `{{pkg}}` as `{{alias}}`?", |
| 501 | ): |
| 502 | """Checks whether student imported a package or function correctly. |
| 503 | |
| 504 | Python features many ways to import packages. |
| 505 | All of these different methods revolve around the ``import``, ``from`` and ``as`` keywords. |
| 506 | ``has_import()`` provides a robust way to check whether a student correctly imported a certain package. |
| 507 | |
| 508 | By default, ``has_import()`` allows for different ways of aliasing the imported package or function. |
| 509 | If you want to make sure the correct alias was used to refer to the package or function that was imported, |
| 510 | set ``same_as=True``. |
| 511 | |
| 512 | Args: |
| 513 | name (str): the name of the package that has to be checked. |
| 514 | same_as (bool): if True, the alias of the package or function has to be the same. Defaults to False. |
| 515 | not_imported_msg (str): feedback message when the package is not imported. |
| 516 | incorrect_as_msg (str): feedback message if the alias is wrong. |
| 517 | |
| 518 | :Example: |
| 519 | |
| 520 | Example 1, where aliases don't matter (defaut): :: |
| 521 | |
| 522 | # solution |
| 523 | import matplotlib.pyplot as plt |
| 524 | |
| 525 | # sct |
| 526 | Ex().has_import("matplotlib.pyplot") |
| 527 | |
| 528 | # passing submissions |
| 529 | import matplotlib.pyplot as plt |
| 530 | from matplotlib import pyplot as plt |
| 531 | import matplotlib.pyplot as pltttt |
| 532 | |
| 533 | # failing submissions |
| 534 | import matplotlib as mpl |
| 535 | |
| 536 | Example 2, where the SCT is coded so aliases do matter: :: |
| 537 | |
| 538 | # solution |
| 539 | import matplotlib.pyplot as plt |
| 540 | |
| 541 | # sct |
| 542 | Ex().has_import("matplotlib.pyplot", same_as=True) |
| 543 | |
| 544 | # passing submissions |
| 545 | import matplotlib.pyplot as plt |
| 546 | from matplotlib import pyplot as plt |
| 547 | |
| 548 | # failing submissions |
| 549 | import matplotlib.pyplot as pltttt |
| 550 | |
| 551 | """ |
| 552 | student_imports = state.ast_dispatcher.find("imports", state.student_ast) |
nothing calls this directly
no test coverage detected