VS Code: from (file) import * not working - python

I'm having the config.py and main.py in the same folder. However, when I try to use from config import *, it would not work and I can access the variables stored in config.py. I'm using python 3.11 from Microsoft Store. Any help is appreciated, thank you!

like nigh-anxiety already mentioned in the comments, it is a really bad practice to import * from something because it can pollute your name space ...
another problem could arise if you have a libary called config which will lead to problems
Best practice would be:
from config import my_var
or if you want everything
import config
print(config.my_var)
important is that the code is in your working directory for imports to work fine else there could be problems ...
and to use
config.my_var
instead of
my_var
is not that big of a deal and will help you keep your namespace clean

Related

What's the Pythonic way of supporting constants across modules in one project as well as across projects? [duplicate]

This seems pretty basic, so I must be missing something obvious. Goal is to import a module from the same directory. I've broken it down about as simple as I can and I'm getting the nameerror.
file import_this.py:
def my_function(number) :
print number + 2
file import_test.py:
import import_this
my_function(2)
Do I have to specify the directory the import file is in? (It's in the same as the test file). Also, can I test to see what modules are imported?
You are accessing the function incorrectly.
Either use the following
import import_this
import_this.my_function(2)
or do,
from import_this import my_function
my_function(2)
Alternatively (apart from #mu's answer above),
>>>import import_this as it
.. and then,
>>> it.my_function(2)

Import all modules from folder, execute function from all of them with known name

Well, I have pretty hard task and I'm completely stucked, like in any direction.
What program should do:
Import all modules (names are random) from folder
MainScript.py
modules/
mod1.py
mod2.py
mod3.py
...
Execute specific (known name, and everywhere it's same) function.
mod1.main()
mod2.main()
mod3.main()
...
As I understand it, I should list all files in folder , then make list with them and for each [x] in list import module and execute script. I've found that modules[0].main() works only if modules[0] no string, so, it should be modules[0]=main not modules[0]='main'. So and there I need somehow deal with it... but for import I don't know...
I've already googled about it, only found https://stackoverflow.com/a/1057534/10289135
And I guess it will not work for me (I also don't understand how it works and script didn't work for me)
Any ideas?
You can use the following syntax:
from filename(remove the .py) import *
This is a wild card import it imports every thing from a module literally everything .By doing this you dont need to do the work like 'filename.blabla' ,but simply you can do 'blabla'.
import os
import sys
import importlib
modules = []
for i in os.listdir("C:\\Windows\\path\\to\\your\\modules\\"):
mod = i
modules.append(mod)
sys.path.append("C:\\Windows\\path\\to\\your\\modules\\")
for i in modules:
i = i[:i.find(".")]
module = importlib.import_module(f"{i}")
module.main()

How to import custom module the same way as pip-installed modules?

I feel really dumb asking this question, but it's a quirk of python I've put up with for awhile now that I finally want to fix.
On CentOS 7, given that I have "roflmao.py" and "__init__.py" in the directory:
/usr/lib/python2.7/site-packages/roflmao
Why is it that when I'm using the python interpreter (and not in the directory containing roflmao.py), I must type:
from roflmao import roflmao
Instead of simply:
import roflmao
To gain access to "roflmao.py"'s functions and variables? I can import re, collections, requests, or any PIP-installed module just fine, but not my own custom one.
How can I set things up to accomplish this?
Put from roflmao import * into __init__.py.
If you do this, then you don't really need to use roflmao.py. Because it would then be pointless to do from roflmao import roflmao. So it's best to just put the code from roflmao.py into __init__.py.

Python Import Module on Raspberry Pi

I know this has been asked dozens of times but I can't see what in the world I'm doing wrong. I'm trying to import a module in python 2.7 from a different directory. I would greatly appreciate some input to help me understand why this method doesn't work. I have the following directory structure on my raspbian system:
/home/pi/
...projects/__init__.py
...projects/humid_temp.py
...python_utilities/__init.py__
...python_utilities/tools.py
I'm calling humid_temp.py and I need to import a function within tools.py This is what their contents look like:
humid_temp.py:
import os
import sys
sys.path.append('home/pi/python_utilities')
print sys.path
from python_utilities.tools import *
tools.py:
def tail(file):
#function contents
return stuff
The print sys.path output contains /home/pi/python_utilities
I'm not messing up my __init__.py's am I?
I've also ruled out possible permission issues with that path as I gave it full 777 access and I still hit the
ImportError: No module named python_utilities.tools.
What did I miss?
When you want to import something like -
from python_utilities.tools import *
You need to add the parent directory of python_utilities to sys.path , not python_utilities itself. So, you should add something like -
sys.path.append('/home/pi') #Assuming the missing of `/` at start was not a copy/paste mistake
Also, just a note, from <module> import * is bad , you should consider only importing the required items, you can check the question - Why is "import *" bad? - for more details.
In humid_temp.py, just write:
from python_utilities import tools
There is no need for appending subfolder to sys.path.
Then when you want to use functions from tools, just
tools.function()

Load A Separate Codefile in Python

I have two codefiles in python, let's say mainfile.py and separatecode.py. I would like to run separatecode.py from within mainfile.py, referencing the specific directory where separatecode.py is stored.
So the pseudocode of what I am looking to do would be something like:
import C:\Users\Jack\Documents\MyFolder\separatecode.py
A number of questions discuss importing, but I can't find one that discusses importing a specific file you wrote in a particular directory. I would like to be able to use functions defined in separatecode.py and am looking for the equivalent of the source("separatecode.r") command in R if that helps.
Add that directory to your sys.path by doing:
import sys
sys.path.append('/directory/to/my/file')
Import the module as normal:
import separatecode
The code you used will not work. It will give a syntax error.
Look at the documentation for the import statement, especially the grammar. A module is one or more identifiers separated by dots.
You can make import separatecode work by adding C:\Users\Jack\Documents\MyFolder to the PYTHONPATH environment variable. This will make it available to all Python scripts. Or you can add that path to sys.path in mainfile.py before importing separatecode.
Try something like this:
import imp
foo = imp.load_source('Module_name', 'Path\To\module.py')
foo.MyClass()
you dont need the foo.MyClass() it was just an example to show that the module works like any other module
no you can import a module from anywhere using the path and its name and you can acsess all its functions etc
for anything else check out:
Python Imp
I hope this is what you were looking for

Categories

Resources