I've written a basic program with a couple of classes, and I've had two issues I would like help with. All of the files are in the same directory, and my classes are in files with the same name as the class.
First, my class files can only import with the format
from module import class
I can't use the format
import module
Second, I've only been able to use my classes if I do the import inside of main. When I import at the beginning of the file, I get an unboundlocalerror when creating an object. I've had these issues (especially the 1st one) on more than one program. Any ideas?
Thanks!
You cannot, as you found out, use
import class
You either have to use
from module import class
And you'd call the class simply as
class # note you don't have the module namespace
Or if you'd like to keep the namespace (which I'd recommend)
import module
Then you can say
module.class
module.otherclass
...etc
As you found, you cannot just type:
import class
as that would lead python to believe that you wanted to import a module named class, when what you want is the class inside the module. That is why
from module import class
does work, as it shows python where 'class' is.
Related
How would one go about importing only a specific class from a Python module using its path?
I need to import a specific class from a Python file using the file path. I have no control over the file and its completely outside of my package.
file.py:
class Wanted(metaclass=MyMeta):
...
class Unwanted(metaclass=MyMeta):
...
The metaclass implementation is not relevant here. However, I will point out that it's part of my package and I have full control over it.
Import example:
spec = importlib.util.spec_from_file_location(name='Wanted', location="path_to_module/mudule.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
This works, and Wanted is imported. The problem is that Unwanted is also imported. In fact, as long as there is any string value given for name (including an empty string), both Wanted and Unwanted are imported from the module.
This has the same effect as in the example before, where both Wanted and Unwanted are imported:
importlib.util.spec_from_file_location(name='random string', location="path_to_module/mudule.py")
I'm not looking for a specific solution using importlib; any reasonable way will do. I will point out that I don't have a need of using the class when it's imported, I only need the import to happen and my metaclass will take care of the rest.
If I am not mistaken, the name parameter is just used to name the module you are importing. But, more importantly, when you are importing any module, you are executing the whole file, which means that in your case both of these classes will be created. It would not matter whether you wrote from file import Wanted, import file or used any other form of the import statement.
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
Source: https://docs.python.org/3/reference/executionmodel.html#structure-of-a-program
since you named your file "file.py":
from file import Wanted
If your file is in a folder, you can use:
from folder.file import Wanted
I've inherited some code with imports in each function and using underscores for each module imported as below
def my_func():
from foo import bar as _bar
from spam import meat as _meat
# Do some work
What is the point in the _bar? All imports are done like this.
If the actual names are things that exist as a part of the built in commands in python, this is done as a way to avoid shadowing those built in functions (for example - from mymodule import open would make the built in open which returns file handles inaccessble). Otherwise, it's simply convention for the original author.
I believe functions with name starting with a single underscore can't be imported using this line :
from module import *
for example this module :
def _some_function_1():
pass
def some_function_2():
pass
if you imported this module, you will be able to access only some_function_2()
I was writing a code in python and got stuck with a doubt. Seems irrelevant but can't get over it. The thing is when I import a module and use it as below:
import math
print math.sqrt(9)
Here I see math(module) as a class which had a method sqrt(). If that is the case then how can I directly use the class without creating an object of it. I am basically unable to understand here the abstraction between class and and object.
Modules are more like objects, not like classes. You don't "instantiate" a module, there's only one instance of each module and you can access it using the import statement.
Specifically, modules are objects of type 'module':
>>> import math
>>> type(math)
<type 'module'>
Each module is going to have a different set of variables and methods.
Modules are instantiated by Python, whenever they are first imported. Modules that have been instantiated are stored in sys.modules:
>>> import sys
>>> 'math' in sys.modules
False
>>> import math
>>> 'math' in sys.modules
True
>>> sys.modules['math'] is math
True
AFAIK all python modules (like math and million more) are instantiated when you have imported it. How many times are they instantiated you ask ? Just once! All modules are singletons.
Just saying the above statement isn't enough so let's dive deep into it.
Create a python module ( module is basically any file ending with ".py" extension ) say "p.py" containing some code as follows:
In p.py
print "Instantiating p.py module. Please wait..."
# your good pythonic optimized functions, classes goes here
print "Instantiating of p.py module is complete."
and in q.py try importing it
import p
and when you run q.py you will see..
Instantiating p.py module. Please wait...
Instantiating of p.py module is complete.
Now have you created an instance of it ? NO! But still you have it up and running ready to be used.
In your case math is not a class. When you import math the whole module math is imported. You can see it like the inclusion of a library (the concept of it).
If you want to avoid to import the whole module (in order to not have everything included in your program), you can do something like this:
from math import sqrt
print sqrt(9)
This way only sqrt is imported and not everything from the math module.
Here I see math(module) as a class which had a method sqrt(). If that is the case then how can I directly use the class without creating an object of it. I am basically unable to understand here the abstraction between class and and object.
When you import a module, the module object is created. Just like when you use open('file.txt') a file object will be created.
You can use a class without creating an object from it by referencing the class name:
class A:
value = 2 + 2
A.value
class A is an object of class type--the built-in class used to create classes. Everything in Python is an object.
When you call the class A() that's how you create an object. *Sometimes objects are created by statements like import creates a module object, def creates a function object, classcreates a class object that creates other objects and many other statements...
I'm looking to import all the classes from one Python file to the other?
In the class you wish to import from, include a variable called __all__, and fill it with the names of the classes/variables you want.
__all__ = ['Class1', 'Class2', 'variable_i_want']
In the class you wish to import them to, you may use the asterisk to gain access to all of the classes.
from foo import *
As suggested, be careful of name collisions when doing this.
Just import the file like any other
import mythings
Then you can use
myClass = mythings.MyClass()
In addition to what the other people are saying, the file you are importing must exist somewhere in sys.path. (usually your current directory is in there, so same directory imports are no problem) For example, if you want to import from your parent directory:
#want to import ../myotherfile.py
import os
import sys
sys.path.append(os.path.abspath(os.pardir))
import myotherfile
print(myotherfile.func())
from module import *
You must be careful when doing this as you can get name collisions.
I keep noticing blocks of code starting with import string, import re or import sys.
I know that you must import a module before you can use it. Is the import based on the object?
The import is based on what module you want to access the names of.
Python has modules that give the code more functionalities. import re gives access to the re module which gives RegEx support. If you type help() at the Python interpreter and then type modules, it will return a list of all the modules.
import sys
Will have the effect of adding a sys variable to your local namespace (usually at the module level). Because sys is a module with it's own attributes, then you can say sys.something(), and Python will be able to reference the local name sys, and then the attribute something, and then call it ().
from os.path import join
This will look inside the os package, inside the path subpackage, and create a local reference to the join function in your namespace. That way, you can simply refer to it as:
join('a', 'b')
Suggest you look at a couple of tutorials that cover importing.