Supposing I have written a set of classes to be used in a python file and use them in a script (or python code in a different file). Now both the files require a set of modules to be imported. Should the import be included only once, or in both the files ?
File 1 : my_module.py.
import os
class myclass(object):
def __init__(self,PATH):
self.list_of_directories = os.listdir(PATH)
File 2 :
import os
import my_module
my_module.m = myclass("C:\\User\\John\\Desktop")
list_ = m.list_of_directories
print os.getcwd()
Should I be adding the line import os to both the files ?
How does this impact the performance, supposing there are lots of modules to be imported ? Also, is a module ,once imported, reloaded in this case ?
Each file that you are using a module in, must import that module. Each module is its own namespace. Things you explicitly import within that file are available in that namespace. Thus, if you need os in both files, you should import them in both files.
Related
Is there another way to write it other than doing it in two separate lines like this?
from os.path import isfile, isdir
from os import scandir # or import os.scandir
TL;DR You can't. You got only that method from os.path import <stuff> if you wanna import the functions/objects from inside of os.path.
When you import stuff using just import you can import only modules (module is a term for python file containing python objects). To import the objects inside of a module you use from to traverse upto that module, and then you use import <whateverObject> to import that object from that file (anything and everything is an object in python, as long as it's inside a .py file). The . you use is (generally) to traverse through the directories ('sub' packages?) inside of a package.
How does the interpreter know which directory to include in a package, or how to recognise a given directory as a package? It looks for an __init__.py file inside it. If it finds one, it is a package, and thus you can import it.
import is limited to accessing directories and modules at most, if used alone. When you use from <module_or_directory> import <objects>, the task of accessing directories and/or modules is handed over to the clause after from, and the clause after import takes over the task of looking for python objects inside of the module. You see, these are two distinct things - 1) accessing a file/directory, which comes under file system, and 2) accessing the contents of a file, (specifically, a .py file), which comes under python's domain - neatly separated in the from-import style of importing stuff.
In the case of the os module, os.path is another .pyi file (ntpath.pyi on Windows) that is alias-ed in the os.py file as path. Since it is a module, it goes in the clause after from in from os.path import isfile, isdir. Whereas scandir is a function in os module, hence it goes in the clause after import in from os import scandir.
I'm working on my first project and am trying to figure out how something works. If I have a module that store some functions I will reference in my main program that depend on another module, where do I include the import statement?
For example:
# Title: func.py
import os
def my_function(path):
if not os.path.isfile(path):
parser.error(f'The file {path} does not exist.')
Do I include import os here, or can I simply have it in the main document?
You must import the module in the file that references the module. So if you have a file that somewhere calls os.path.isfile, you need to import os at the top of that file.
-- comment by larsks
One of the ways I recently started structuring my programming is by having one main file and multiple different appropriately named files that represent different parts of the project that I am working on.
All different Python Files in one folder.
To then use one file I would simply type:
import filename
This works all well and good, but I noticed that I can't use variables from within another file in that code.
My question is can I import variables, or pass variables from one file to another to make use of them later again?
Each file you import is considered to have its own namespace. You can reference anything in that namespace if you prefix it with the module name.
For example, f you have a file like this:
# filename.py
foobar = 42
You can access foobar with filename.foobar. For example:
import filename
print("foobar is %s" % filename.foobar)
Another way is to use __builtin__ module so that your file main_file.py will contain:
print(thing)
while your whatever.py will contain:
import __builtin__
__builtin__.thing = 1
import main_file
More on that: here
In python 2 I can create a module like this:
parent
->module
->__init__.py (init calls 'from file import ClassName')
file.py
->class ClassName(obj)
And this works. In python 3 I can do the same thing from the command interpreter and it works (edit: This worked because I was in the same directory running the interpreter). However if I create __ init __.py and do the same thing like this:
"""__init__.py"""
from file import ClassName
"""file.py"""
class ClassName(object): ...etc etc
I get ImportError: cannot import name 'ClassName', it doesn't see 'file' at all. It will do this as soon as I import the module even though I can import everything by referencing it directly (which I don't want to do as it's completely inconsistent with the rest of our codebase). What gives?
In python 3 all imports are absolute unless a relative path is given to perform the import from. You will either need to use an absolute or relative import.
Absolute import:
from parent.file import ClassName
Relative import:
from . file import ClassName
# look for the module file in same directory as the current module
Try import it this way:
from .file import ClassName
See here more info on "Guido's decision" on imports in python 3 and complete example on how to import in python 3.
I have a Python module and I'd like to get that modules directory from inside itself. I want to do this because I have some files that I'd like to reference relative to the module.
First you need to get a reference to the module inside itself.
mod = sys.__modules__[__name__]
Then you can use __file__ to get to the module file.
mod.__file__
Its directory is a dirname of that.
As you are inside the module all you need is this:
import os
path_to_this_module = os.path.dirname(__file__)
However, if the module in question is actually your programs entry point, then __file__ will only be the name of the file and you'll need to expand the path:
import os
path_to_this_module = os.path.dirname(os.path.abspath(__file__))
I think this is what you are looking for:
import <module>
import os
print os.path.dirname(<module>.__file__)
You should be using pkg_resources for this, the resource* family of functions do just about everything you need without having to muck about with the filesystem.
import pkg_resources
data = pkg_resources.resource_string(__name__, "some_file")