niyander-logo

Niyander Tech

Learn with fun

  • All Coursera Quiz Answers

Programming Assignment: Import and Scope Solution

In this article i am gone to share Coursera Course: Programming in Python by Meta Week 4 | Programming Assignment: Import and Scope Solution with you..

Programming Assignment: Import and Scope

Introduction.

So far, you’ve learned the different ways in which you can use import statements to import other Python files, modules and packages. You have also seen the different ways in which you can import specific functions using different formats of import.

  • Use the import statement to import a built-in package in Python.
  • Use the import statement to call a function present in another Python file.

Learn how to use import to bring external code within direct scope of the project.

Instructions:

  • Step 1: Open the file jsongenerator.py present inside project folder.
  • Step 2: Import a built-in package called json.
  • Step 3: Import the following from a file called employee.py:

A function called details

Variables called employee_name, age and title

  • Step 4: Implement the create_dict() function that returns a dictionary given employee information.

4.1 Create and return a dictionary with three key-value pairs where

keys are string variables – “first_name”, “age” and “title” and their respective values are employee_name, age and title variables that we have imported from the employee module. Be sure to cast the values to the expected types.

  • Use a function called dumps() from the json module using dot notation and pass the employee_dict dictionary that we have created to it. Return its value to a variable named json_object.
  • The format of the same should look like:
  • variable = json.dumps(dict)
  • 6.1 Use a built-in function called open() and pass the output_file argument and “w” to it. Return the value of this function to a variable named newfile.
  • 6.2 Call a function called write() over this variable newfile. Pass the json_object variable you created in Step 5 inside it.
  • 6.3 Close this file by calling a built-in function close() directly on newfile. You don’t need to pass any arguments here.
  • Step 7: Save the files.
  • Step 8: Open the terminal to execute the files.
  • Step 9: Run the code using the command (within project directory)
  • python3 jsongenerator.py

Copy and paste this code..

jsongenerator.py

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • GDPR Privacy Policy
  • Privacy Policy
  • Terms and Conditions

Greetings, Hey i am Niyander, and I hail from India, we strive to impart knowledge and offer assistance to those in need.

Logo image

  • Suggest edit

Modules, import mechanism, namespaces, scope(s)

Modules, import mechanism, namespaces, scope(s) #.

In this chapter we will dive into one of the most important features of python: the import mechanism. We will explain why modules are useful, how to “import” them, and how you can write one yourself.

Variable scopes #

The scope of a variable is the region of the program where the variable is valid, i.e. the “location” where the variable name can be used to refer to the data it links to. Let’s consider this first example:

It doesn’t work because the name i is defined in the function foo , which we defined but never called (you can see this because nothing is printed), so the function’s statements were actually never run.

Let’s see if the following example works better:

Here, the function is called and i is defined and equal to 5. However, the scope of the variable i is the block defined by the function foo : outside of this scope the variable doesn’t exist anymore, leading to the NameError at the global scope.

If this is understood, the following example might be clear as well?

The global scope refers to the highest scope level (the module or, in interactive mode, the interpreter). The function’s scope in turn is called local scope . One says that the global scope prevails because what is possible in one direction isn’t possible in the other:

Yes, k is available in foo() : global variables are also available in the nested local scopes. They can be overridden locally (like in the example above), but this change won’t be visible at the global scope level.

Python modules are used to store a collection of functions and variables that can be imported into other modules or into the main environment .

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

For instance, I used my favorite text editor to create a file called greetings.py with the following content:

greetings.py:

I copied this file into the current working directory (this “detail” is important, as we will see below). From the (i)python interpreter I can now import this module with the following command:

By importing the module, I have access to the functions it contains:

But also to the global variables defined at the top level:

Exercise 10

Repeat the steps above on your laptop and do additional experiments / ask questions until these variable scope mechanisms are well understood.

Namespaces #

Global variables in modules or scripts are useful, but they should be used with care . Indeed, since they are available from everywhere in the module, the namespace can quickly become “polluted”: for large modules, it becomes hard to keep track of all variables. This can become even more complicated when new modules with their own new variables and functions are used as well.

Fortunately, the global scope is constrained to the current script or module, and using external modules is unlikely to cause confusion thanks to the import mechanism:

By importing the math module (available in python’s standard library ), we have access to a new variable called math . The variable math has the type module , and provides new functions and variables (such as math.pi ). What are all these functions and variables? Let’s use the built-in dir() function to find out:

Exercise 11

Ask the ipython documentation about dir (remember how?)

Like our greetings module, the math module contains functions (e.g. math.radians ) as well as variables (e.g. math.nan or math.pi ). For Python there is no fundamental difference between variables and functions: they are all simply attributes of the math module and therefore listed by dir (we’ll get back to attributes later: for now, remember the dot . syntax, dir and TAB autocompletion). Some of the attributes listed by dir have a prefix of two underscores __ . We’ll get back to them soon.

There are several ways to import a module. See these four examples:

All four options lead to the same result: they compute the sine of π/2.

Now, which one to use? It is up to you, but there are some implicit rules (conventions) which are widely accepted:

In case of doubt, use option A. It is the most readable and the most explicit .

The exception to the first rule is when the library has a naming convention for its acronym. A good example is numpy , which recommends to use import numpy as np .

Option C might be useful if the names you are importing are very explicit, and if you expect to use them often in your script. Otherwise, it is not recommended.

Option D is bad. Don’t use it.

You can make an exception to rule 4 when working in the command line and exploring data. Never use option 4 in scripts.

Exercise 12

Try to find arguments why option D is a bad idea.

But how does python know where to look for modules when you type import mymodule in the interpreter? Well, it relies on a mechanism very similar to linux’s PATH environment variable. Remember this one? Within python, the directories where the interpreter will look for modules to import are listed in sys.path :

Similar to the linux PATH mechanism, python will look into each of these directories in order . The first directory is always the current working directory (an empty string), the rest of the list may vary depending on your environment. When a file called mymodule.py is found, it is imported once (and only once) and added to the sys.modules variable, effectively telling python that the module has already been imported. This means that if you change the file and import it again, nothing will change . Fortunately, there are ways to avoid this behavior (see below).

As you can see, there are many folders related to mambaforge , the tool we used to install python. This makes sense, because we want python to look for modules related to our installation of python (not the one used by our operating system). In particular, the site-packages folder is of interest to us. If you look into this folder using the linux command line or ipython’s magic commands (remember how?) you’ll find the many packages we already installed together last week.

You can edit sys.path at your wish and add new folders to it, exactly as you would with the PATH environment variable in linux. In practice, however, it is recommended to use standard folders to install your packages instead of messing around with sys.path . I personally never had to change sys.path in my scripts, but it can come handy if you want to use a collection of modules that you have not “packaged” yet: in this case, you can put all modules in a folder and add it to sys.path with:

But this will add the folder to the current session or script only. To add a folder permanently, you can use the PYTHONPATH environment variable.

Exercise 13

Print your own sys.path on your laptop and explore the folders listed there.

Now let’s play with sys.path a little. Create a fake module called matplotlib.py in your current working directory. Open a python interpreter and import matplotlib . Which of the modules (the official or the fake one) is loaded by python, and why?

Because of this “feature”, it is important to find meaningful (and unique) names for your own modules (don’t forget to delete the fake matplotlib module after trying that out!).

Note: the “matplotlib trick” above does not work with modules of the standard library, because built-in modules are imported as part of the interpreter’s startup process.

Reimporting modules #

Of course, there is a lot more behind an import statement than this short summary (see the documentation for a more comprehensive overview). What you should remember however is that an import statement is not computationally cheap: it has to look for a file among many folders, compile the python code to bytecode, add the module to a registry… Actually, for all the things it does, it is quite fast already!

Since import statements are used all the time in Python, it is a good idea to optimize them: therefore, Python will not re-import a module that is imported already.

Most of the time this is not a problem, but sometimes (mostly in interactive development) it might be useful to make changes to a module and having them available at the command line without having to restart a fresh Python interpreter each time. To do this, there are two mechanisms available to you:

Using Python’s importlib.reload() function:

This can reimport a module which has been imported before (i.e. it won’t search for it again). But this has to be done each time you change a module, making it quite cumbersome in interactive mode. Here again, ipython comes with a more flexible solution:

Using ipython’s autoreload extension:

From now on, autoreload will make sure that all modules are reloaded automatically before entering the execution of code typed at the ipython prompt.

Executing modules as scripts #

You’ve already learned that importing modules actually runs them, the same way as $ python mymodule.py (from the linux terminal) or %run mymodule.py (in ipython) would. This can have some undesired consequences: what if, for example, you would like certain things to happen when the module is run as script but not when being imported?

There is a mechanism that allows to do exactly this. Add the following block of code at the end of the greetings.py module:

Now you can execute your script like this:

But importing it will produce no output:

How does this work exactly? The important bit is the if __name__ == '__main__': line. __name__ (and all other attributes starting and ending with two underscores) is “reserved” by the language. They are no different than other variables, but you should not erase or replace them since they contain useful information and might be used by other tools. For example:

Now, back to our script: the statement if __name__ == '__main__' is going to be false when the module is imported (since the name is greetings ), but obviously true when the module is run as a script. Indeed, __name__ is set to __main__ when executed.

Take home points #

variables are defined in a scope , and we learned about two scopes: local and global . There are precise rules as to how each scope can interact with the other. As a general rule: global variables are available in nested scopes and cannot be overwritten, and local variables are not available in the global scope.

the import mechanism is useful to avoid namespace pollution . Modules come with their own namespace, and it is recommended to keep each module’s namespace clean (i.e. no from XYZ import * )

python borrowed the PATH mechanism from linux and uses a similar logic to look for modules and packages. Installing a new module is therefore super easy: just put a mymodule.py at the right place. (and don’t mess with the existing modules!)

the %autoreload command from ipython allows to dynamically change a module while using it at the command line

when writing scripts, always put the code that needs to be executed in an if __name__ == '__main__' block: that way, your script can still be imported for the functions it proposes

Help Articles

Solve problems with programming assignments, learner help center dec 5, 2022 • knowledge, article details.

If you're having problems with a programming assignment, check for your issue below.

If your problem is with a different kind of assignment, or you don't see your issue here, check our assignment troubleshooting page.

Can't submit programming assignment

If you're having trouble submitting a programming assignment, try the following steps:

  • Make sure you saved your files in the correct format. To change the format, re-save your files.
  • Decrease the size of the files, if possible.
  • Clear your browser's cookies and cache.
  • Making sure any ad-blocking software is turned off on your browser or network.
  • Ask your peers for help by posting in the course discussion forums. Many programming assignment issues have very specific requirements, so people in the same course will be able to help you more than Coursera's support team.

No grade on programming assignment

If the assignment uses custom grading, it will take up to an hour to get your grades back.

If you've waited longer than an hour and still don't have a grade:

  • Check the assignment instructions and make sure you have saved your files in the right format.
  • Resubmit the assignment.

Understanding your grade

Because many programming assignment graders use complex logic that the instructor creates, the Coursera support team can’t explain or change programming assignment grades.

To understand your grade on a programming assignment, review the assignment instructions and any feedback you got.

You can also discuss any questions with your peers in the course discussion forums.

Assignment not marked complete

Weeks that include programming assignments may still say in progress even after you've successfully completed the assignment.

Check your Grades tab to confirm that you've successfully completed the assignment.

Token issues

If you're having trouble with a token not syncing or not showing up, try 

  • Making sure your ad-blocking software is turned off on your browser or network
  • Making sure you are logged in with the correct account
  • Clearing your cache and cookies
  • Using a different browser or new browser window
  • Check if your computer’s clock is set accurately

Related Articles

  • Number of Views 47.95K
  • Number of Views 36.95K
  • Number of Views 69.25K
  • Number of Views 81.41K
  • Number of Views 100.48K

programming assignment import and scope

© 2021 Coursera Inc. All rights reserved.

programming assignment import and scope

Table of Contents

Creating a programming assignment, submitting work on students' behalf, creating and using an autograder file, manual grading, regrading submissions, using code similarity.

  • ​Assignment Workflow

Programming Assignments

To create a programming assignment, go to the course’s Assignments page and click  Create Assignment  in the bottom right of the page. Select Programming Assignment from the list of assignment types.

Students can successfully upload up to 256 individual files (or in a zip folder) and a total of 100MB in Gradescope directly, or they can submit larger files using a Github or Bitbucket integration. You can then autograde the code, manually grade it with a rubric and in-line comments, or use a combination of autograding and manual grading. 

Submitting a Programming Assignment

  • Open your assignment. Click the left side panel to expand it (if it isn’t already) and select  Manage Submissions . This will take you to a list of submissions that have been made to this assignment so far.
  • Click the  Upload Submission  button at the bottom of the screen. A dialog box will appear.
  • Drag and drop your code file(s) into Gradescope.
  • Submit a GitHub or Bitbucket repository. For this method, you will first need to connect your account if you have not already. You will then be prompted to choose the repository and branch. You can upload as many files as you’d like, including files of different types.
  • Next, select the student’s name from the dropdown menu at the bottom of the dialog box.
  • Then, select  Upload to submit your student’s work.

With our autograder platform, you have full flexibility in setting up whatever language, compilers, libraries, or other dependencies you need. You provide us with a setup script and an autograder script, along with whatever supporting code you need, and we manage accepting student submissions, running your autograder at scale, and distributing the results back to students and to you.

As an instructor, you can create a new programming assignment on Gradescope and upload your autograder zip file using our  autograder specifications . Your code produces output in the format that we request. Students submit to Gradescope and have their work evaluated on demand. They can submit as many times as they want and get results back as soon as the autograder finishes running.

If you update your autograder after students have submitted, you can rerun it on all submissions at once from the assignment’s  Manage Submissions  page.

Submission interface showing autograder test results and submitted code

You can also grade students’ code manually using the Gradescope grading interface. To enable manual grading, check the “Enable Manual Grading” box when creating a programming assignment. You can also enable this on the settings page for an existing assignment. Your students can then upload their code, and you can grade it from the Grade Submissions tab, using a rubric and in-line comments. Note that students won’t be able to see any scores or feedback from manual grading until you Publish Grades from the assignment’s Review Grades page. 

If manual grading is enabled for a programming assignment, you can indicate one or more manually graded questions on the assignment’s Edit Outline page. You can have both autograded and manually graded components on one programming assignment, or you can skip the Configure Autograder step, set the Autograder question on the Edit Outline page to be worth 0 points, and only use manual grading to grade students’ code. Rerunning the autograder on any (or all) submissions will preserve any manual grading.

programming assignment import and scope

Regardless of whether you’re using Autograding, Manual Grading, or a combination of the two, once submissions are in, you can download all students’ code submissions in bulk by selecting the  Assignment  >  Review Grades  (left side panel) >  Export Submissions  (lower right corner). 

If the autograder score for programming submissions needs to be recomputed or rescored, you’ll find a  Rerun Autograder  button on the assignment’s Manage Submissions page as well. Rerunning the autograder will only rescore the most recent and active submission. Any manual grading will remain unaffected.

In any Programming Assignment, you can also use the Code Similarity tool, which will help determine commonalities among your students’ code. This tool does not automatically detect plagiarism but rather shows you how similar programming submissions are to each other. Code similarity is available for both autograded and manually graded assignments and for most programming languages. For more information on checking for similarity among your students’ submitted programming assignments, check out the full guide on  Code Similarity .

Was this article helpful?

Assignment types, bubble sheet assignments, related articles, file requirements, how does gradescope handle late assignment submissions.

 Logo

logo

Scientific Programming

  • suggest edit

Modules, import mechanism, namespaces, scope(s)

Modules, import mechanism, namespaces, scope(s) #.

In this chapter we will dive into one of the most important features of python: the import mechanism. We will explain why modules are useful, how to “import” them, and how you can write one yourself.

Variable scopes #

The scope of a variable is the region of the program where the variable is valid, i.e. the “location” where the variable name can be used to refer to the data it links to. Let’s consider this first example:

It doesn’t work because the name i is defined in the function foo , which we defined but never called (you can see this because nothing is printed), so the function’s statements were actually never run.

Let’s see if the following example works better:

Here, the function is called and i is defined and equal to 5. However, the scope of the variable i is the block defined by the function foo : outside of this scope the variable doesn’t exist anymore, leading to the NameError at the global scope.

If this is understood, the following example might be clear as well?

The global scope refers to the highest scope level (the module or, in interactive mode, the interpreter). The function’s scope in turn is called local scope . One says that the global scope prevails because what is possible in one direction isn’t possible in the other:

Yes, k is available in foo() : global variables are also available in the nested local scopes. They can be overridden locally (like in the example above), but this change won’t be visible at the global scope level.

Python modules are used to store a collection of functions and variables that can be imported into other modules or into the main environment .

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

For instance, I used my favorite text editor to create a file called greetings.py with the following content:

greetings.py:

I copied this file in the current working directory (this “detail” is important, as we will see below). From the (i)python interpreter I can now import this module with the following command:

By importing the module, I have access to the functions it contains:

But also to the global variables defined at the top level:

Exercise 10

Repeat the steps above on your laptop and do additional experiments / ask questions until these variable scope mechanisms are well understood.

Namespaces #

Global variables in modules or scripts are useful, but they should be used with care . Indeed, since they are available from everywhere in the module, the namespace can quickly become “polluted”: for large modules, it becomes hard to keep track of all variables. This can become even more complicated when new modules with their own new variables and functions are used as well.

Fortunately, the global scope is constrained to the current script or module, and using external modules is unlikely to cause confusion thanks to the import mechanism:

By importing the math module (available in python’s standard library ), we have access to a new variable called math . The variable math has the type module , and provides new functions and variables (such as math.pi ). What are all these functions and variables? Let’s use the built-in dir() function to find out:

Exercise 11

Ask the ipython documentation about dir (remember how?)

Like our greetings module, the math module contains functions (e.g. math.radians ) as well as variables (e.g. math.nan or math.pi ). For Python there is no fundamental difference between variables and functions: they are simply all attributes of the math module and therefore listed by dir (we’ll get back to attributes later: for now, remember the dot . syntax, dir and TAB autocompletion). Some of the attributes listed by dir have a prefix of two underscores __ . We’ll get back to them soon.

There are several ways to import a module. See these four examples:

All four options lead to the same result: they compute the sinus of π/2.

Now, which one to use? It is up to you, but there are some implicit rules (conventions) which are widely accepted:

In case of doubt, use option A. It is the most readable and the most explicit .

The exception to the first rule is when the library has a naming convention for its acronym. A good example is numpy , which recommends to use import numpy as np .

Option C might be useful if the names you are importing are very explicit, and if you expect to use them often in your script. Otherwise, it is not recommended.

Option D is bad. Don’t use it.

You can make an exception to rule 4 when working in the command line and exploring data. Never use option 4 in scripts.

Exercise 12

Try to find arguments why option D is a bad idea. If you can’t find any reason, ask me !

But how does python know where to look for modules when you type import mymodule in the interpreter? Well, it relies on a mechanism very similar to linux’s PATH environment variable. Remember this one? Within python, the directories where the interpreter will look for modules to import are listed in sys.path :

Similar to the linux PATH mechanism, python will look into each of these directories in order . The first directory is always the current working directory (an empty string), the rest of the list may vary depending on your environment. When a file called mymodule.py is found, it is imported once (and only once) and added to the sys.modules variable, effectively telling python that the module has already been imported. This means that if you change the file and import it again, nothing will change . Fortunately, there are ways to avoid this behavior (see below).

As you can see, there are many folders related to miniconda , the tool we used to install python. This makes sense, because we want python to look for modules related to our installation of python (not the one used by our operating system). In particular, the site-packages folder is of interest to us. If you look into this folder using the linux command line or ipython’s magic commands (remember how?) you’ll find the many packages we already installed together last week.

You can edit sys.path at your wish and add new folders to it, exactly as you would with the PATH environment variable in linux. In practice, however, it is recommended to use standard folders to install your packages instead of messing around with sys.path . I personally never had to change sys.path in my scripts, but it can come handy if you want to use a collection of modules that you have not “packaged” yet: in this case, you can put all modules in a folder and add it to sys.path with:

But this will add the folder to the current session or script only. To add a folder permanently, you can use the PYTHONPATH environment variable.

Exercise 13

Print your own sys.path on your laptop and explore the folders listed there.

Now let’s play with sys.path a little. Create a fake module called matplotlib.py in your current working directory. Open a python interpreter and import matplotlib . Which of the modules (the official or the fake one) is loaded by python, and why?

Because of this “feature”, it is important to find meaningful (and unique) names for your own modules (don’t forget to delete the fake matplotlib module after trying that out!).

Note: the “matplotlib trick” above does not work with modules of the standard library, because built-in modules are imported as part of the interpreter’s startup process.

Reimporting modules #

Of course, there is a lot more behind an import statement than this short summary (see the documentation for a more comprehensive overview). What you should remember however is that an import statement is not computationally cheap: it has to look for a file among many folders, compile the python code to bytecode, add the module to a registry… Actually, for all the things it does, it is quite fast already!

Since import statements are used all the time in Python, it is a good idea to optimize them: therefore, Python will not re-import a module that is imported already.

Most of the time this is not a problem, but sometimes (mostly in interactive development) it might be useful to make changes to a module and having them available at the command line without having to restart a fresh Python interpreter each time. To do this, there are two mechanisms available to you:

Using Python’s importlib.reload() function:

This can reimport a module which has been imported before (i.e. it won’t search for it again). But this has to be done each time you change a module, making it quite cumbersome in interactive mode. Here again, ipython comes with a more flexible solution:

Using ipython’s autoreload extension:

From now on, autoreload will make sure that all modules are reloaded automatically before entering the execution of code typed at the ipython prompt.

Executing modules as scripts #

You’ve already learned that importing modules actually runs them, the same way as $ python mymodule.py (from the linux terminal) or %run mymodule.py (in ipython) would. This can have some undesired consequences: what if, for example, you would like certain things to happen when the module is run as script but not when being imported?

There is a mechanism that allows to do exactly this. Add the following block of code at the end of the greetings.py module:

Now you can execute your script like this:

But importing it will produce no output:

How does this work exactly? The important bit is the if __name__ == '__main__': line. __name__ (and all other attributes starting and ending with two underscores) is “reserved” by the language. They are no different than other variables, but you should not erase or replace them since they contain useful information and might be used by other tools. For example:

Now, back to our script: the statement if __name__ == '__main__' is going to be false when the module is imported (since the name is greetings ), but obviously true when the module is run as a script. Indeed, __name__ is set to __main__ when executed.

Take home points #

variables are defined in a scope , and we learned about two scopes: local and global . There are precise rules as to how each scope can interact with the other. As a general rule: global variables are available in nested scopes and cannot be overwritten, and local variables are not available in the global scope.

the import mechanism is useful to avoid namespace pollution . Modules come with their own namespace, and it is recommended to keep each module’s namespace clean (i.e. no from XYZ import * )

python borrowed the PATH mechanism from linux and uses a similar logic to look for modules and packages. Installing a new module is therefore super easy: just put a mymodule.py at the right place. (and don’t mess with the existing modules!)

the %autoreload command from ipython allows to dynamically change a module while using it at the command line

when writing scripts, always put the code that needs to be executed in an if __name__ == '__main__' block: that way, your script can still be imported for the functions it proposes

Chelsea Troy

Chelsea Troy

How to implement variable assignment in a programming language.

I’m working my way through  Crafting Interpreters . The project guides programmers through building their  own  interpreters for the Lox programming language. I started writing a blog series about my progress.  You can see all the posts so far right here .

In the  last post covering part of Chapter 7, we talked about error handling, at that time largely in the context of parsing and interpreting expressions.

Now in Chapter 8 we get into some of the fun stuff—state.

programming assignment import and scope

I have talked about state a couple of times in the past on this blog—in particular, here , during the series about the book Structure and Interpretation of Computer Programs. If you like this series, you’ll probably like that one 😉.

The short version:

Procedural code without state—for example, a stateless function—amounts to a series of substitution operations in which an argument name serves as a placeholder that gets substituted at runtime with the passed-in inputs. The same inputs always result in the same output, and this makes the function “pure.” (In Crafting Interpreters , Bob Nystrom points out what we’re all thinking: that the programmers who wax poetic about their devotion to dispassionate logic also label said functions with such weighty language as “pure.”)

Add state, though, and this changes . Bob equates the presence of state to the Lox programming language’s “memory.” And just like a human memory, it influences statements’ behavior. The result from print a depends on what we assigned to a .

It also means that the programming language has to recognize a , which we can accomplish by:

  • Parsing some assignment syntax like var a = "Hallo!"
  • Interpreting that assignment syntax by assigning a key a in a key-value store to point to the value "Hallo!"

The key-value store doesn’t have to be all that fancy.

In the 80 line Scheme interpreter that we talked about in this previous post , we use a plain Python dictionary for the task. In fact, Python itself used dicts to delineate scope in early versions ( here’s the PEP where Python solidified the thrust of their current approach to state scoping, back in version 2.1). In Crafting Interpreters , Bob does similar:

The Environment class wraps a plain Java HashMap . Two methods wrap the HashMap ‘s put and get functions with semantically relevant names. That’s it.

This implementation of Environment supports only global scope: there’s one environment, all its variables are accessible everywhere, and either they’re in there or they’re not. Later, when we endeavor to include nested scopes, Environment gets a new attribute—a reference to another Environment , set to nil for the global scope—and when a variable is referenced, the environments check themselves and then, recursively, their enclosing environments, until they reach the global one.

I’ll bring up that SICP post one more time here because we do something similar in that implementation, although we copy the parent environment rather than referencing it:

For nested expressions, our nested environments are recursively passed through, first to  seval  (which evaluates expressions), then back into a new environment if evaluation reveals another procedure. …we’re slapping our new local env on top of a copy of the existing environment, and for a huge environment that will be really space inefficient. We’ve talked on this blog before about a similar situation:  tracking nested transactions in an implementation of an in-memory database . If this were a real interpreter and not a toy for learning purposes, I might turn to a solution like that one. Note that the nested scopes wouldn’t face that annoying deletion snafu we faced with the database: local scopes can overwrite the values of variables from broader scopes, but they don’t delete them.

So the implementation isn’t super clever.

P.S. If you’re interested in trying out implementing a nested scope yourself, I gotchu! Here’s an interactive activity that I wrote for my Python Programming students to practice implementing database transactions for a pet shop database (complete with fun, dancing parrots!). It’s level-appropriate for someone who is comfortable using dictionaries/hashmaps/associative arrays in at least one modern (last updated after 2012) object-oriented programming language. To get this running locally, go to your command line and do:

  • git clone https://github.com/MPCS-51042/materials.git
  • cd materials
  • pip install jupyter (there’s also a pipfile if you’re a pipenv user, but I don’t want folks who aren’t regular Pythonistas to have to screw around with virtual environments just to try this exercise)
  • jupyter notebook (this is going to open a tab in your browser with a list of folders)
  • Navigate to materials > database_efficiency_exercise > 2_Transactions_(Space_Efficiency).ipynb
  • The file is a REPL: you can run any of the code cells with SHIFT + ENTER. I recommend starting by going to the top bar and clicking Kernel > Restart and Run All. This will run the code I have provided so you have the Table implementation available in scope, for example.
  • Try out the activity! I have tried to make the instructions as clear as possible and would welcome feedback on whether you were able to complete the exercise on your own 😊

A simple implementation does not mean an absence of decisions, by the way.

From this chapter of Crafting Interpreters about variable declaration and assignment, one of the things I most appreciated was the time that Bob took to consider the decisions that programming language authors make about how variable referencing and assignment work. Let’s go over some of those decisions:

1. Will the language use lexical or dynamic scope for variables?

That is, will the are over which the variable is defined by visible in the structure of the code and predictable before runtime ( lexical scope )? In most modern programming languages, it is. But we can see an example of dynamic scope with methods on classes. Suppose we have two classes that each possess a method with the same signature, and a function takes in either of those two classes as an argument. Which of the twin methods is in scope at runtime depends on which class the argument passed to the function is an instance of. That class’s method is in scope. The other class’s method is not in scope.

Lexical scope allows us to use specific tokens to identify when to create a new child environment. In Lox, we use curly braces for this {} , as do Swift and Java. Ruby also functions with curly braces, although using do..end is more idiomatic. Python determines scope with level of indentation.

2. Will the language allow variable reassignment?

If we want immutable data that has no chance of changing out from under a programmer, then we can insist that the value of a variable remain the same after it is created until it is destroyed. Haskell does its best to force this, and constants in many languages aim to provide this option.

Most programming languages allow for mutable variables, though, that programmers can define once and then reassign later. Many of them distinguish these from constants with a specific keyword. For example, JavaScript provides const for immutable constant declaration and var for mutable variable declaration. Swift does the same with let and var . Kotlin does it with val and var (“var” is a very popular choice for this).

3. Will the language allow referencing undeclared variables?

What happens if a programmer says print a; and no a has been declared? Lox raises an error at compile time. Ruby, by contrast, allows it. In Ruby, puts a where a is not declared will print nothing, but it won’t error out. puts a.inspect will print nil . Bob calls this strategy “too permissive for me” in the chapter. I…tend to agree, but I also don’t relish being all the way at the other end, say, at Java 6, where we had to null check everything in perpetual fear of the dreaded Null Pointer Exception.

I’m a fan of the Optional paradigm that we’ve seen in some more modern programming language implementations like Java 8, Swift, and Kotlin. I want to know if a variable could be null so I can handle it appropriately.

4. Will the language allow implicit variable declaration?

Lox distinguishes between declaring a new variable ( var a = "What's"; ) and assigning it a new value ( a = "Up?" ;). Without that var keyword, it will assume the intent is to reassign, and it will raise an error at compile time because the variable is not yet declared.

Ruby and Python, by contrast, assume that an assignment to a variable that does not yet exist means declare it . So a = 1 in Ruby sets 1 to a if a is nil, and reassigns a to point to 1 if it was previously pointing to something else.

Convenient, for sure. But in my experience, this does open programmers up to more scope-related insidious bugs because an initialization of a local variable and a reassignment of a global one look the same.

Languages might always differ on some of these questions.

And that’s okay: different languages serve different purposes and different communities. A programming language author can establish and communicate a perspective on a language’s purpose and use cases, then allow those decisions to drive implementation choices.

If you liked this piece, you might also like:

This talk about what counts as a programming language , explained with a raccoon stealing catfood from a cat…somehow

The Raft series, of course!  Learn to implement a distributed system from the comfort of your home, complete with gifs and smack talk!

Lessons from Space: Edge Free Programming —about what launchpads have in common with software, and what that means for you and your work!

Share this:

Leave a reply cancel reply.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Discover more from Chelsea Troy

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

shopie14/Coursera-Assignment-Programming-in-Python-by-Meta

Folders and files.

  • Python 100.0%

COMMENTS

  1. Programming Assignment: Import and Scope Solution

    Step 1: Open the file jsongenerator.py present inside project folder. Step 2: Import a built-in package called json. Step 3: Import the following from a file called employee.py: A function called details. Variables called employee_name, age and title. Step 4: Implement the create_dict () function that returns a dictionary given employee ...

  2. GitHub

    Use a built-in function called open() and pass the output_file argument and "w" to it. Return the value of this function to a variable named newfile. Call a function called write() over this variable newfile. Pass the json_object variable you created in Step 5 inside it. Close this file by calling a built-in function close() directly on ...

  3. Programming Assignment: Import and Scope Coursera

    #viral #trending #coursera #courseracertificate #problemsolving My Facebook profile-https://www.facebook.com/isratjahan.tisha.547Subscribe free!!! click here...

  4. Lab Instructions: Import and Scope

    \n \n \n. Complete the write_json_to_file() function \n \n; Use a built-in function called open() and pass the output_file argument and "w" to it. \nReturn the value of this function to a variable named newfile. \n; Call a function called write() over this variable newfile. Pass the json_object variable you created in Step 5 inside it. \n

  5. Modules, import mechanism, namespaces, scope(s)

    Yes, k is available in foo(): global variables are also available in the nested local scopes. They can be overridden locally (like in the example above), but this change won't be visible at the global scope level. Modules#. Python modules are used to store a collection of functions and variables that can be imported into other modules or into the main environment.

  6. python import and scope

    0. when you import a module, it will not only give you access to what you have just imported. It will also execute the whole script. This is why you can see in many script. if __name__ == '__main__': some code. otherwise, some code would be executed on import. So all the function of the module are declared, and all the 'out of function' code is ...

  7. Programming in Python Course by Meta

    There are 5 modules in this course. In this course, you will be introduced to foundational programming skills with basic Python Syntax. You'll learn how to use code to solve problems. You'll dive deep into the Python ecosystem and learn popular modules, libraries and tools for Python. You'll also get hands-on with objects, classes and ...

  8. jask89738/Programming-Assignment-Import-and-Scope

    All the quiz answers for the Programming Assignment: Import and Scope will be provide week wise - GitHub - jask89738/Programming-Assignment-Import-and-Scope: All the quiz answers for the Programming Assignment: Import and Scope will be provide week wise

  9. Python Scope & the LEGB Rule: Resolving Names in Your Code

    Understanding Scope. In programming, the scope of a name defines the area of a program in which you can unambiguously access that name, such as variables, functions, objects, and so on. A name will only be visible to and accessible by the code in its scope. Several programming languages take advantage of scope for avoiding name collisions and unpredictable behaviors.

  10. Variables and scope

    By default, the assignment statement creates variables in the local scope. So the assignment inside the function does not modify the global variable a - it creates a new local variable called a, and assigns the value 3 to that variable. The first print statement outputs the value of the new local variable - because if a local variable has ...

  11. Solve problems with programming assignments

    Can't submit programming assignment. If you're having trouble submitting a programming assignment, try the following steps: Make sure you saved your files in the correct format. To change the format, re-save your files. Decrease the size of the files, if possible. Clear your browser's cookies and cache. Making sure any ad-blocking software is ...

  12. Programming Assignments

    Creating a Programming Assignment. To create a programming assignment, go to the course's Assignments page and click Create Assignment in the bottom right of the page.Select Programming Assignment from the list of assignment types.. Students can successfully upload up to 256 individual files (or in a zip folder) and a total of 100MB in Gradescope directly, or they can submit larger files ...

  13. jask89738/Programming-Assignment-Import-and-Scope-Solution

    Programming Assignment: Import and Scope Solution. Contribute to jask89738/Programming-Assignment-Import-and-Scope-Solution development by creating an account on GitHub.

  14. Modules, import mechanism, namespaces, scope (s)

    There are several ways to import a module. See these four examples: # A # Import an entire module and access its attributes with a "dot" import math math.sin(math.pi/2) 1.0. # B # Same as A, but store the module under a new variable named "ma" import math as ma ma.sin(ma.pi/2) 1.0.

  15. Python "import" scope

    with. boo = __import__('boo') ( __import__ is a builtin function of the Python interpreter that either imports a module, or looks up a reference to the existing module if it's already been imported, and returns that reference) Whatever is automatically generating boo.py is doing it wrong. It should be adding import foo somewhere within that file.

  16. {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":"Programming Assignment: Abstract Classes and Methods Week 3","path":"Programming Assignment ...

  17. How to Implement Variable Assignment in a Programming Language

    The result from print a depends on what we assigned to a. It also means that the programming language has to recognize a, which we can accomplish by: Parsing some assignment syntax like var a = "Hallo!" Interpreting that assignment syntax by assigning a key a in a key-value store to point to the value "Hallo!"

  18. Getting-started-with-TensorFlow-2-Coursera/Week 4 Programming ...

    Contribute to GSNCodes/Getting-started-with-TensorFlow-2-Coursera development by creating an account on GitHub.

  19. Programming Basics: Variable declaration, intitialiation, assignment

    Initialisation: The name used for the first assignment of a variable, before initialisation, a variable has a default value, in the case of objects, those objects have a null value. Initialisation can be done in conjunction with declaration. Scope: The "lifespan" of a variable, a variable is in scope until the end of the code block, at which ...

  20. shopie14/Coursera-Assignment-Programming-in-Python-by-Meta

    Languages. Python 100.0%. Contribute to shopie14/Coursera-Assignment-Programming-in-Python-by-Meta development by creating an account on GitHub.