Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: importing another .py file

I have a class and I want to import a def function by doing:

import <file>

but when I try to call it, it says that the def can not be found. I also tried:

from <file> import <def>

but then it says global name 'x' is not defined.

So how can I do this?

Edit:

Here is a example of what I am trying to do. In file1.py I have:

var = "hi"

class a:
  def __init__(self):
    self.b()

  import file2

a()

and in file2.py I have:

def b(self):
  print(var)

it is just giving me a error though.

like image 488
user2638731 Avatar asked Jul 31 '13 17:07

user2638731


People also ask

Can two Python scripts import each other?

You might have code that you want to both run on its own and import from other scripts. In that case, it's usually worthwhile to refactor your code so that you split the common part into a library module. While it's a good idea to separate scripts and libraries, all Python files can be both executed and imported.

How do you import a program into Python?

The Python import statement imports code from one module into another program. You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist.


1 Answers

import file2

loads the module file2 and binds it to the name file2 in the current namespace. b from file2 is available as file2.b, not b, so it isn't recognized as a method. You could fix it with

from file2 import b

which would load the module and assign the b function from that module to the name b. I wouldn't recommend it, though. Import file2 at top level and define a method that delegates to file2.b, or define a mixin superclass you can inherit from if you frequently need to use the same methods in unrelated classes. Importing a function to use it as a method is confusing, and it breaks if the function you're trying to use is implemented in C.

like image 147
user2357112 supports Monica Avatar answered Oct 14 '22 23:10

user2357112 supports Monica