importing without executing the class - python
Asked Answered
A

6

7

my problem is about i have a file that contain class and inside this class there is bunch of code will be executed

so whenever i import that file it will executed ! without creating an object of the class ! , here is the example

FILE X

class d:
    def __init__(self):
        print 'print this will NOT be printed'
    print "this will be printed"

file B

import x

output is this will be printed, so my question is how to skip executing it until creating a new object?

Astyanax answered 17/8, 2012 at 17:10 Comment(5)
"How to skip executing until creating a new object" -- why not put it in __init__ like the other one?Capua
why not just put the second print in the __init__ method? i think __init__ could be what you're looking for, since it is by definition the code is run on object creationMunoz
well because the real class is a lot bigger than the example it's around 350 line so it's hard to re modified itAstyanax
Agree with @Capua and @EmmettJButler. When Python imports a module, it executes the module-level code, including building the class definition with the class methods, etc. Therefore when you import X, and class d's definition gets built (so you can call it from B), it executes the code inside of the class. Usually this means you'll have class-level variables set and unbound methods ready to be attached to instances, but in your case it means that statement will be printed. Someone better versed in Python than I can correct me/better state this :)Roumell
Posted an answer and then read the comments. @Roumell is correct. The only thing missing to make that comment an answer is "...so refactor your code into methods". RD, if you post that as an answer I'll +1 you.Shaky
S
3

You can't do that in Python, in Python every class is a first level object, a Python class is an object too and an class attribute can exist even if there is no instances of that class. If you just want to suppress the output of the print statement you can redirect the output of your print statements on the importing moment or create a context like the one provided in this first answer and use the __import__ statement manually.

Shuddering answered 17/8, 2012 at 17:23 Comment(0)
R
1

If all you want to do is suppress the print (or any other executable statements) during import, surround them with a check for top module execution:

if __name__ == '__main__':
    print 'this will be printed'

This will prevent the print during import, but allow it when the module is executed interactively.

Readytowear answered 17/8, 2012 at 19:0 Comment(4)
it's not working ,, i've tried to create an object but it's not printing the statementAstyanax
To get the line to print, I executed: python -i x.py. To suppress the print, I executed: python -i b.py. Please show the code you tried this with and let me know how you invoked it.Readytowear
The OP wants to know "how to skip executing it until creating a new object", not depending on whether the module has been imported or not. I somehow missed that until just now myself.Boucicault
Missed that, too. In that case the suggestion made by numerous others to move the code to init or similar seems like the best solution.Readytowear
B
1

As others have pointed out, the second print statment is executing because it's one of the suite of statements making up the class declaration -- all of which are executed when the module they're in is imported because the declaration is part of its top-level code verses it being nested inside a function or method.

The first print statement isn't executed because it's part of a method definition, whose statements don't execute until it's called --- unlike those within a class definition. Typically a class's __init__() method is called indirectly when an instance of the class is created using the class's name, which would be d() for one named d like yours.

So, although it contradicts what's in the text of the strings being displayed, to make that second print statement only execute when instances of the class are created (just like with the first one) you'd need to also make it part of the same method (or called by it). In other words, after doing so, neither of them will execute when the file the class is in is imported, but both will when any instances of the class are created. Here's what I mean:

File x.py:

class d:
    def __init__(self):
        print 'print this will NOT be printed'  # not true
        print "this will be printed when object is created"

File b.py:

import x  # no print statements execute
obj = d()  # both print statements will be executed now
Boucicault answered 18/8, 2012 at 0:54 Comment(0)
E
1

Your question is like: I have a function

def f():
    print(1)
    print(2)

How do I make print(1) executed, but not print(2)? There is really no easy way. What you have to understand is that def __init__(self) is also a statement. Your class consists of that statement and print statement. There is no easy way to execute one but not the other. Of course, if you can change the source of the class, just put the print inside __init__, where it will be called after instance creation.

Endosmosis answered 9/5, 2014 at 9:17 Comment(0)
R
0

(Copied from a comment above in case it is useful to future readers)

Agree with @mgilson and @EmmettJButler - this code is likely best-placed in the __init__. When Python imports a module, it executes the module-level code, including building the class definition with the class methods, etc. Therefore when you import X, and class d's definition gets built (so you can call it from B), it executes the code inside of the class. Usually this means you'll have class-level variables set and unbound methods ready to be attached to instances, but in your case it means that your statement will be printed.

As suggested by the others, refactoring the code is likely your best bet.

Roumell answered 17/8, 2012 at 17:53 Comment(0)
H
0

I also face this when two modules try to execute scripts on same SQLite db. What I did was put one import of certain class inside a function body where it normally use.

Fount this in https://docs.python.org/3/faq/programming.html

"It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option.

Only move imports into a local scope, such as inside a function definition, if it’s necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module."

Hyehyena answered 15/7 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.