Displaying an object atributes in pycharm - python

The pycharm doesn t displaying the prints
PyCharm doesn't display the atribute values of my class

You are missing: if __name__ == '__main__':
Suppose your code is in test.py file:
class P:
def __init__(self, attr):
self.a = attr
p = P(4)
if __name__ == '__main__':
print(p.a)
Run it using python test.py or via PyCharm and you will see 4 in output.
Reason:
When you execute your Python script, Python interpreter sets the variable __name__ to '__main__', the condition __name__ == '__main__' evaluates to True and print function is executed.
When you import test.py as a module in another module, the interpreter sets __name__ to test and the print function call won't be executed.
Refer to What does if name == “main”: do? for more details.

Related

Python relative import variable name error [duplicate]

I created two files, and when I run a.py, result is {'1': '1'}, it's correct. however, running b.py, the result is none. How can I get the value of requests from b.py?
a.py:
requests = {}
def set_value():
global requests
requests["1"] = "1"
if __name__ == "__main__":
set_value()
print(requests)
b.py:
import a
def get_value():
print(a.requests)
if __name__ == "__main__":
get_value()
if __name__ == "__main__": means that the code following it will only be executed when the file is called explicitly with python3 filename.py from the command line. Since you are simply importing your file and not executing it, the global variable is never set.
Also, python variables are all "global" variables when declared outside of a function, and the global keyword is only needed when you want to declare a global variable inside of a function.
To fix this, change a.py to the following:
requests = {}
def set_vale():
requests["1"] = "1"
set_vale()

Why is the if __name__ == "__main__": main() pattern used instead of putting the main code in the if statement?

Although I've been using python for a while, and a common pattern you see is these two statements:
def main():
# Fancy code here
if __name__ == "__main__":
main()
My question is, why wouldn't you use this pattern instead?
if __name__ == "__main__":
# Fancy code here
Is this just in case you want to import main from another place? Or is there some other reason you might want to do this?
Another reason is to avoid populating the global scope with variables.
Consider this example:
def add_em(arg1, arg2):
return a + b
if __name__ == "__main__":
a = 2
b = 4
print(add_em(a, b))
Here, the add_em() function clearly has a bug: it should return arg1 + arg2, but since the a and b variables belong to the global scope, this bug will likely go undetected until add_em() is called from another context. Running the script gives no error:
$ python myscript.py
6
Using a main() function would likely detect this earlier:
def add_em(arg1, arg2):
return a + b
def main():
a = 2
b = 4
print(add_em(a, b))
if __name__ == "__main__":
main()
Now the error is detected right away:
$ python myscript.py
Traceback (most recent call last):
...
NameError: name 'a' is not defined
A function is reusable, you can call it from other code. Code under the if __name__ guard can't so be invoked.
It makes testing and encapsulation easier. All you need is
import module
module.main()

if __name__ == '__main__' function call

I am trying to work around a problem I have encountered in a piece of code I need to build on. I have a python module that I need to be able to import and pass arguments that will then be parsed by the main module. What I have been given looks like this:
#main.py
if __name__ == '__main__'
sys.argv[] #pass arguments if given and whatnot
Do stuff...
What I need is to add a main() function that can take argument(s) and parse them and then pass them on like so:
#main.py with def main()
def main(args):
#parse args
return args
if __name__ == '__main__':
sys.argv[] #pass arguments if given and whatnot
main(sys.argv)
Do stuff...
To sum up: I need to import main.py and pass in arguments that are parsed by the main() function and then give the returned information to the if __name_ == '__main_' part.
EDIT
To clarify what I am doing
#hello_main.py
import main.py
print(main.main("Hello, main"))
ALSO I want to still be able to call main.py from shell via
$: python main.py "Hello, main"
Thus preserving the name == main
Is what I am asking even possible? I have been spending the better part of today researching this issue because I would like to, if at all possible, preserve the main.py module that I have been given.
Thanks,
dmg
Within a module file you can write if __name__ == "__main__" to get specific behaviour when calling that file directly, e.g. via shell:
#mymodule.py
import sys
def func(args):
return 2*args
#This only happens when mymodule.py is called directly:
if __name__ == "__main__":
double_args = func(sys.argv)
print("In mymodule:",double_args)
One can then still use the function when importing to another file:
#test.py
import mymodule
print("In test:",mymodule.func("test "))
Thus, calling python test.py will result in "In test: test test ", while calling python mymodule.py hello will result in "In mymodule: hello hello ".

The difference between __main__ and launch() methods

I'm still in the learning phase and I have this question.
So in order to execute a class, we use if __name__ == '__main__': and call the class as the following
class Example():
def test(self):
print "Hello There"
if __name__ == '__main__':
Example()
However, I saw some classes that use def launch(): instead of if __name__ == '__main__':, so the question here: Are they similar so I can both ways or def launch(): has a special propose?
Thank you.
Python runs anything in the top level this is why we use classes and functions to separate jobs (among other reasons).
So for example here
Script a.py
def main():
pass
main()
The interpreter will define a function called main() but when it reaches the main() call in the top level (aligned left most)
it will execute the main function.
Now in the case of your launch()
if __name__ == '__main__':
Example()
vs
__name__ = __main__
This is used in the case where someone wants to import a program or class but doesn't want it to run when the interpreter runs into it.
Import a will call the main() at that point and time
however let's say b.py is structurally similar but instead of main() it has __name__ = __main__, b.py won't run unless directly called.
The reason I bring this is up is because as #harshil9968 pointed out, Python has no "launch" method. What likely was happening is they defined a launch() method instead of main()
Then put it under a class
class A():
def launch(self):
#actions
if __name__ == '__main__':
A()
Call to A() calls the launch() method within the A class.

if __name__ == '__main__' not working ipython

I'm having trouble getting the if __name == '__main__' trick to work in an IPython, Spyder environment. I've tried every approach given in this thread:
if __name__ == '__main__' in IPython
Here are my super simplified modules
Module1.py
Class UnitTest():
print 'Mod1 UnitTest!'
if __name__ == '__main__':
UnitTest()
Module2.py
import Module1
Class UnitTest():
print 'Mod2 UnitTest!'
if __name__ == '__main__':
UnitTest()
So I run Module2.py and I always am seeing both Mod2 UnitTest and Mod1 UnitTest printed. These are executing in an IPython kernel. I want only the Mod2 UnitTest message to display.
Any idea what's up?
Well I deleted this question earlier out of embarrassment but might as well share in case any other newb sees this.
I forgot to put the UnitTest line inside of the __init__ method. So the unit test was being run every single time when the class was defined and not when the object was instantiated. The code should be:
Module1.py
Class UnitTest():
def __init__(self):
print 'Mod1 UnitTest!'
if __name__ == '__main__':
UnitTest()
Module2.py
import Module1
Class UnitTest():
def __init__(self):
print 'Mod1 UnitTest!'
if __name__ == '__main__':
print 'Mod2 UnitTest!'

Categories

Resources