Python error: default variable is not initialized when importing the module

Imagine I have a module called foo.py that includes the following function:

def bar(var=somedict):
    print(var)

In my main program, main.py, I import this module, declare the variable somedict and then execute the function bar:

from foo import *
somedict = 'foobar'
bar()

The goal is to have somedict passed as a default parameter without explicitly specifying it (something I want to avoid for the actual program I am working on).

However, Python raises a

NameError: name 'somedict' is not defined
. How can I still import the module and achieve the desired 'passing along of the default variable'? Thank you!

Answer №1

The variable "somedict" is not defined when importing. Therefore, using <code>from foo import *
will result in the error message
NameError: name 'somedict' is not defined

To resolve this issue, make the following changes to foo.py

somedict={}
def bar(var=None):
    if var is None:
        var=somedict
    print(var)

After making these modifications, you should be able to achieve what you were attempting to do, but in a slightly different manner

import foo
foo.somedict = {'a':1}
foo.bar()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The dictionary's get method is failing to properly retrieve the requested data

My goal is to send a value from a textbox to the server, search for this value in a dictionary, and display the result in a div. For instance, if my dictionary is d = {'a': "1", 'b': "2", 'c': "3"}, and I enter "a" in the text ...

A foolproof method for recording Python code efficiently

Embarking on the documentation of Python 3.3 modules is a new endeavor for me, as I am a beginner in this area. I would greatly appreciate any assistance in choosing the best tool for this task. After researching various topics online, I have come across ...

The action of clicking on the dropdown menu does not yield any results

see image description hereI am new to Python with Selenium and I am practicing. I am attempting to click on a dropdown element, it appears highlighted but does not respond to clicks. Below you will find the code I have used along with a screenshot and th ...

Acquire the website link using Selenium in the Python programming language

As a beginner in Python, I am excited to dive into web scraping and have chosen the following website as my target: Link After some research, I believe that Selenium is the best tool for the job. To get started, I wrote the code snippet below: from selen ...

The email confirmation feature in Flask-Security using Flask-Mail fails to send unless changes are made to the flask_security/utils.py file

Recently, I came across an issue while working with Flask-Security where the confirmation email was not being sent successfully. After some troubleshooting, I managed to resolve it by removing a specific line in flask_security/utils.py. The problematic lin ...

Not adhering to PyTorch's LRScheduler API - Transform function into lambda expression for lr_lambda

Does anyone know how to convert the given lr_lambda def into Lambda format? from torch.optim.lr_scheduler import LambdaLR def cosine_scheduler(optimizer, training_steps, warmup_steps): def lr_lambda(current_step): if current_step < warmup_s ...

Python's IndexError occurs when attempting to access an index that does not exist within a list

Check out the code snippet I've been working on: class MyClass: listt=[] def __init__(self): "" instancelist = [ MyClass() for i in range(29)] for i in range(0,29): instancelist[i].listt[i].append("ajay") print instancelist An ...

shell_plus is experiencing issues with autoload, not loading all of the necessary apps

When I execute ./manage.py shell_pus, here is the output along with my settings.py file: jason@buster:~/projects/mcifdjango$ ./manage.py shell_plus From 'auth' autoload: Permission, Group, User, Message From 'contenttypes' autoload: Co ...

Here are the steps to resolve the error message: "selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element"

I am currently in the process of learning Selenium. My focus is on creating a script that can add multiple items to a shopping cart. Interestingly, when I removed the class from my script, it allowed me to successfully add an item to the cart. However, on ...

Risks associated with storing configuration files in JSON/CPickle are related to security

In search of a secure and flexible solution for storing credentials in a config file for database connections and other private information within a Python module. This module is responsible for logging user activity in the system through different handler ...

Exploring JSON using Python for retrieving selective outcomes

I'm currently trying to solve the problem of traversing JSON in Python using the pre-installed json package and selectively returning the data. Here's an excerpt from the JSON: { "1605855600000": [ { "i ...

Is it possible to extract data from tables that have the 'ngcontent' structure using Selenium with Python?

Scraping basic tables with Selenium is a simple task. However, I've been encountering difficulties when trying to scrape tables that contain "_ngcontent" notations (as seen at "https://material.angular.io/components/table/overview"). My goal is to con ...

Set up scripts to run at regular time intervals without interruption

I am currently working on developing a scheduler that can activate multiple scripts based on specific time intervals. In this case, I have scripts labeled as A, B, and C that need to be triggered at different frequencies - A every minute, B every two minut ...

Python OSError: [Errno 9] Issue with file descriptor encountered upon attempting to open large JSON file

Recently, I attempted to process a large json file (the Wikipedia json dump) in Python by reading it line by line. However, I encountered the following Error: Traceback (most recent call last): File "C:/.../test_json_wiki_file.py", line 19, in ...

Executing numerous test scenarios using a single instance of the Selenium web driver

As a beginner in programming, I kindly ask for your patience as I seek assistance. I am working on creating test cases with Selenium Web Driver to check the functionality of a webpage. The process involves logging in first using a password and later enter ...

Encountering difficulty transforming DataFrame into an HTML table

I am facing difficulties incorporating both the Name and Dataframe variables into my HTML code. Here's the code snippet I have: Name = "Tom" Body = Email_Body_Data_Frame html = """\ <html> <head> </he ...

GAE/P: Streamlining the transition to NDB

After making the transition from db to ndb, I've encountered more challenges than I had expected. I have converted my ReferenceProperty to KeyProperty, but now I need to add explicit get() calls everywhere a ReferenceProperty was used since it was pr ...

Rearrange the positions of the latitude and longitude values in a JSON file without any additional tags

I have a JSON file with the following code snippet. I am looking to swap the latitude and longitude values while keeping the output the same. "path": [ [ -0.662301763628716, 51.48792441079866 ], [ ...

Creating unique message formats for communication between a python client and a socket.io node.js server

Currently, I am attempting to establish communication between a Python client and a Node.js server using Socket.io 0.7. My goal is to send a custom event from the client to the server. To achieve this, I have been referencing the Socket.io documentation o ...

Converting JSON to CSV Using Python

i am currently working with a JSON file structured like this: { "temperature": [ { "ts": 1672753924545, "value": "100" } ], "temperature c1": [ { "ts": 167275392 ...