[New Concept Exercise]: Functions in Python
This issue describes how to implement the functions concept exercise for the Python track.
There is an outdated issue for this exercise with some discussion. It can be found here
The related concept documents can be found here.
β Getting started
If you have not yet created or contributed to a concept exercise, this issue will require some upfront reading to give you the needed background knowledge. Some good example exercises to look at in the repo:
π‘Example Exercisesπ‘ (click to expand)
We also recommend completing one or more of the concept exercises (they're called "learning exercises") on the website.
Please please read the docs before starting. Posting PRs without reading these docs will be a lot more frustrating for you during the review cycle, and exhaust Exercism's maintainers' time. So, before diving into the implementation, please go through the following documents:
General Contributing Docs:
- Contributing to Exercism | Exercism and GitHub | - Contributor Pull Request Guide
- What are those Weird Task Tags about?
- Exercism Formatting and Style Guide
- Exercism Markdown Specification
- Reputation
Documents on Language Tracks and Concept Exercises
- Building Language Tracks: An Overview
- What are Concept Exercises?
- Concept Exercise Specifications
- Concept Exercise Stories
π― Goal
This functions concept exercise is meant to teach a deeper understanding and use of functions in Python. It should also explain how Python treats/views functions (as callable objects), and dig into some of the features that make Python functions unique.
π‘Learning objectives
- Understand more about Python
scopesandnamespaces- understand the difference between the
globalandnonlocalkeywords and when to use them
- understand the difference between the
- Get familiar with the special attributes of Python functions
- Get familiar with best practices when using
return, and the difference between explicit and implicitreturn- functions without an explicit return will return the singleton object
None
- functions without an explicit return will return the singleton object
- Understand what is meant by "functions are first class objects in Python".
- understand that
functionsareobjectsin Python, and that they havetypes - understand that
functionscan be assigned to variables, used in expressions, and stored in various data structures such asdictsorlists - create
functonsthat are assigned to variables, used in expressions, and stored in different data structures. - understand and create
functionsthat are/can be nested inside one another
- understand that
- Understand that Python considers a function a form of
callable object. - Understand that a user-defined
function objectis created by afunction definition.
π€ Concepts
-
callable objects -
first-class functions -
global -
nested functions -
nonlocal -
return,implicit return,explicit return -
scope - special
function attributes
π« Topics that are Out of scope
Concepts & Subjects that are Out of Scope (click to expand)
-
named parameters(these can be touched on if needed) -
default parameters(these can be touched on, if needed) -
arbitrary parameters -
*args & **kwargs -
keyword-only arguments -
/and*for requiring parameter types -
functions-as-arguments(this can be mentioned, but shouldn't be required for the exercise) -
functions-as-returns(_this can be mentioned, but will be covered in-depth inhigher-order functions) -
closures(these will be covered in a different exercise) -
decorators(these will be covered in a different exercise) -
functools.wraps(this is used mostly for decorators) -
functools(this will get its own exercise) -
comprehensions -
generators -
lambda,anonymous functions(these will be covered in a different exercise) -
recursion
β©οΈ Prerequisites
These are the concepts/concept exercises the student needs to complete/understand before solving this concept exercise. Since functions is a "meta" topic, these will probably need to be adjusted to fit the parameters of the exercise.
Prereqs (click to expand)
-
basics -
bools -
comparisons -
lists -
list-methods -
loops -
numbers -
strings -
string-methods
π Resources for Writing and Reference
Resources (click to expand)
- Python Docs: Naming and Binding
- Python Docs: Python Scopes and Namespaces
- Python Docs: Defining Functions
- Function definitions (Python Library Reference)
- Dan Bader: Python s Functions are First-Class
- Real Python: Python Scope & the LEGB Rule
- Stack Overflow: Short Description of Python's Scoping Rules?
- Real Python: Python Inner Functions: What are they Good For?
- Stack Abuse: How to Use global and nonlocal variables in Python
-
The
nonlocalStatement (Python Docs) -
The
globalStatement (Python Docs) - Real Python: The Python return Statement: Usage and Best Practices
- Calls (Python Library Reference)
- Is it a Class or a Function? It's a Callable! (Trey Hunner)
- Callables in Python (Vimal A.R Blog)
- Functions as Objects in Python -- this is a subscription-based medium blog, so not good for hints or links
- Python Datamodel: Types
Exercise Ideas & Stories
Should you need inspiration for an exercise story, you can find a collection here. You can also port an exercise from another track, but please make sure to only to include tasks that actually make sense in Python and that add value for a student. Remove/replace/add tasks as needed to make the concept clear/workable.
π Exercise Files to Be Created
File Detail for this Exercise (click to collapse)
|
βΎοΈ Exercise Metadata - Track
For more information on concept exercises and formatting for the Python track config.json , please see config.json. The track config.json file can be found in the root of the Python repo.
You can use the below for the exercise UUID. You can also generate a new one via exercism configlet, uuidgenerator.net, or any other favorite method. The UUID must be a valid V4 UUID.
-
Exercise UUID :
9f38f70d-48f4-4934-ae6e-d8277ede8edc - concepts should be filled in from the Concepts section in this issue
- prerequisites should be filled in from the Prerequisites section in this issue
πΆ Implementation Notes
-
As a reminder, code in the
.meta/examplar.pyfile should only use syntax & concepts introduced in this exercise or one of its prerequisite exercises. We run all ourexamplar.pyfiles through PyLint, but do not strictly require module docstrings. We do require function docstrings similar to PEP257. See this concept exerciseexemplar.pyfor an example. -
Please do not use comprehensions, generator expressions, or other syntax not previously covered either in the introduction to this exercise, or to one of its prerequisites. Please also follow PEP8 guidelines.
-
In General, tests should be written using
unittest.TestCaseand the test file should be named<EXERCISE-NAME>_test.py.- All asserts should contain a "user friendly" failure message (these will display on the webiste to students, so be as clear as you can).
- We use a
PyTest custom markto link test cases to exercise task numbers. - We also use
unittest.subtestto parameterize test input where/when needed. Here is an example testfile that shows all three of these in action.
-
While we do use PyTest as our test runner and for some implementation tests, please check with a maintainer before using a PyTest-specific test method, fixture, or feature.
-
Our markdown and JSON files are checked against prettier . We recommend setting prettier up locally and running it prior to submitting your PR to avoid any CI errors.
π Next Steps & Getting Help
-
If you'd like to work on this issue, comment saying "I'd like to work on this"(there is no real need to wait for a response, just go ahead, we'll assign you and put a[claimed]label on the issue). - If you have any questions while implementing, please post the questions as comments in here, or contact one of the maintainers on our Slack channel.
Comments for discussion ported from original issue:
@BethanyG Any idea for what you want to see for the exercise here? Any analogous exercise you might want transcribed from another track? I can start looking at the tracks I'm familiar with. Nothing comes to mind right now.
Originally posted by @bobahop in https://github.com/exercism/python/issues/2353#issuecomment-1157775990
Rust uses lasagna, but we use lasagna for basics. Go uses Booking Up For Beauty, but that also makes significant use of string formatting, so it might not be as focused for functions as desired.
Originally posted by @bobahop in https://github.com/exercism/python/issues/2353#issuecomment-1157788607
@bobahop there are a few things to note here:
-
This issue has very outdated links and descriptions and it also pings the attached users every time we make a comment, so I think its best if we close it in favor of a new issue using the new template. I will do that shortly.
-
I have a strong preference for original stories/exercises, unless the port/concept is an almost 1-to-1, as was the case with
bools. That isn't to say that porting is verboten, but I'd much rather have a purpose-built exercise than a shoehorned one. We have had trouble in the past with contributors trying to port something and then getting stalled because they were not able to transfer some core piece to Python. -
As I've mentioned, this exercise is quite far "down" the exercise tree. It should not be considered an exercise on how to make functions in Python, but rather as a setup to both
higher order functionsand related concepts. So we should try to think of something that deepens a student's understanding/use of functions, and exercises some of the features unique to Python. Otherwise, this may as well be a practice exercise or a concept-only topic.
I'll add some thoughts/ideas to the new issue.
Originally posted by @BethanyG in https://github.com/exercism/python/issues/2353#issuecomment-1157841911
So this wouldn't be a port of the tasks, but if you like the lasagna story, lasagna master from go could be used and the tasks replaced/adapted/added to.
Secrets on the Elixir track looks like it has a good setup, and that the tasks might be adaptable to Python scenarios. They will probably need a lot of replacing, but could work.
Likewise, Library Fees could be adapted, but the instructions and introduction to the exercise would have to be amended to cover whatever datetime functions or operations were needed for completion.
New Passport could be adapted, but not to use with, because that really really belongs in its own exercise. However, I think the tasks could be changed to make it about assigning functions to variables, calling functions from other functions, nesting, and scope. It could also be renamed "adventures at the DMV" and made ... dystopian ... where the story is about getting in and getting out of the DMV in the fastest way possible, or avoiding cranky employees by finding and excuse to be in the "quick processing" line.
Pizza Pricing holds some promise, but again - the tasks would have to be re-done for Python.
Really, you could use just about any story here. The problematic bit is coming up with 4-6 tasks that cover the concept.
If sudden purpose-built inspiration strikes, I'll update.
Sound like many promising leads. I'm a bit remiss on researching the tracks, as I'm also slowly slogging through crafting interpreters. Very slowly.
I like the dystopian DMV idea... a lot.
Creating an "Adventures at the DMV" story would have the added benefit of carrying a story credit (and a legendary badge). π
Inspiration: https://www.youtube.com/watch?v=ONFj7AYgbko. You could even borrow (with credit) the premise from Zootopia - the DMV is populated by Sloths, and any mistake not only sends you to a new line...but then you have to deal with the Sloths.
Might need some brief background on what DMV stands for, but I think globally most people understand horrible bureaucracy, so it wouldn't take much.
I think I'll start to work up some files tomorrow. And you're getting author credit, too, since it's your story idea.
What do you think of the title "Della's Delays at the DMV"?
"Della's Delays at the DMV" is great. A personal ambition of mine is to have as many alliterative concept exercise titles as possible.
I just looked over the learning objectives and concepts and I winced a bit at global and nonlocal. Is it okay to include them in a way that shows how they can be problematical? Or should we leave them just in the about.md and not give the student experience in them as if they are something encouraged to be done?
Apologies. Had some things to take care of this afternoon, so am late with replying to things.
I just looked over the learning objectives and concepts and I winced a bit at
globalandnonlocal.Is it okay to include them in a way that shows how they can be problematical?
I think for the exercise, it's important to provide students the opportunity to practice using both global and nonlocal in an appropriate or "safe" fashion (heavy guardrails). It doesn't have to be elaborate, and it doesn't have to be much more than a basic mimic (I am thinking of something similar to how we set up error handling messaging in a lot of practice exercises ).
And I think for the instructions/introduction, it would be great to put cautions in, and examples of why it can be a bad idea. Although my thinking here is that if the task or tasks set up a "proper" or "good" use case, the students will more than likely find the foot-gun, and that will convey a really good lesson, about scope, using the keywords, AND about how the Python ethos is to say "we are all adults here, so you need to think through your choices, Python's not going to do that for you."
It does seem somewhat "unfair" to set up students like that ... but I don't know that we teach them fluency by hiding the warts of the language. While we do do that to some extent early on, by the time students are getting ready to feed functions to other functions, use recursion, nest functions, and all the other goodness that comes along with FP paradigms in Python, they should have a working sense of caution, and be building a sense of why endless mutability can be problematic.
So my thought is that maybe there is a task that has them reach out and modify/update a global constant. Or create a global in a function that other functions could read/access (and modify at peril). I'm less clear on the nonlocal, although that could be done with an inner function -- and would be a quite legitimate (if minority) use-case.
...and thinking out loud here..... I don't know if we want to consider a mutability topic, or if we want to (like we have with error handling) insert messages and reminders about the dangers of mutability as we build out the exercises in the functions and higher order functions cluster ... as well as the classes, class-customization, class-interfaces cluster.
While stale, this issue should remain open.
Arg. This keeps falling off the radar. Will do better this week!
I still think it is a good idea, but I am just focused on other things. I also have an idea for a practice exercise, but that is on the back burner as well.
I won't have time before this weekend I don't think - but I am going to PR turning off the stale bot, since none of us on the track are moving very fast these days (which is OK!). Right now, if we comment on anything and 22 days pass, the critter wakes up and flags things as abandoned. It's starting to not be useful, so. π