Transition from MATLAB to Python [duplicate] - python

This question already has answers here:
Import folder of modules in Python
(3 answers)
Closed 7 years ago.
I know this question has been asked before but I can't make heads or tails of what the answer means.
I am making the transition from MATLAB to Python. In MATLAB I can write my own functions and use them in my code. I know I can do the same thing in Python. But I am having a hard time figuring out how to do it.
What I would like to do it create a file with multiple function definitions and then import it into Python like any other module.
First, is this the proper way of thinking it about it? Or do I just need to create multiple definition files for each function?
Second, if it is the proper way of thinking about it how do I access the file? I know you have to set the PYTHONPATH. I have looked at it and where it is looking makes no sense to me.
As an Example: I created a folder called User. In it I have a python function called ted.py. I put said file where the rest of the library files are located (as in numpy or scipy). I want to import the file called User. How can I do this?
After working with Python for awhile I get it. As long as the file is in the same directory and you use the import properly you can use one , some or all of the function definitions in the file.

You have an un-matlab-like (matlab-unlike? dis-matlab-like?) option of putting multiple function definitions into the same .py file. Once the file -- say, fundefs.py -- is on your path, possibly through having issued import sys; sys.path.append('path/to/fundefs');, you can import it
through import fundefs, after which you can access the functions therein by fundefs.fun1, fundefs.fun2 etc.
through from fundefs import *, which will throw all the functions into your current namespace. This is generally discouraged (and frowned upon) for larger modules as it will pollute your namespace, but for a few functions of your own this might just be what you're after. See also this very informative answer (and also comments therein).
as a middle ground through import very_long_and_descriptive_module_name as shorthand to access your functions as shorthand.fun1, shorthand.fun2 etc. (in the obvious case if your definitions are in the file very_long_and_descriptive_module_name.py)

You don't import User. What you want is to import ted. Typically, you would put ted.py in the same folder as your main python file, not in a separate folder.

Related

How to properly import a Python package in PyCharm? [duplicate]

This question already has answers here:
Why import when you need to use the full name?
(8 answers)
Closed 1 year ago.
I'm new to PyCharm, and after downloading a Python package (Manim) my code won't recognize the methods used in the package, unless I very precisely tell it where to look. In other words, when trying to just import Manim, I get this:
where PyCharm even seems to indicate that it doesn't need the two gray lines, as it has already imported Manim. The problem is the errors (underlined in red), they point to classes and/or methods from the Manim package, but are not recognized until I precise:
How can I optimize my imports so that one line suffices for all that's concerning Manim? (This works fine with just from manimlib import * using Spyder3 editor.)
As #Mike Scotty pointed out in his comments, import * and from a import * are generally bad ideas, since python won't know what to import, especially if there are multiple classes with the same name.
An IDE not complaining does NOT mean, your code runs smoothly.
You have several options here:
Having a rather large import list (which is by no means wrong) as you have in your second picture.
Using import manimlib and having rather long function/class calls: intro_words = manimlib.mobject.svg.text_mobject.Text
It's possible to bunch similar imports together like this:
from manimlib.mobject import geometry.Polygon as Polygon, svg.text_mobject.Text as Text
To my humble knowledge, the most pythonic way to go, is having very specific imports, even if that means you'll end up with a large import list. To add to this, most IDEs like PyCharm, Atom or Visual Studio have ways collapsing large import lists into one line:
for example PyCharm does this: import ... which displays all imports by clicking on it.
Refer to pythons documentation on imports and pythons documentation on modules to get a better understanding on how imports work.

What is the good way to deal with python import? [duplicate]

This question already has answers here:
Can't import my own modules in Python
(14 answers)
Closed 2 years ago.
I am working in python3 for a year now and I still don't get the import system....
I always put the empty init.py file on each folder.
But however if my project start to have nested directories (and it append a lot and often) I have to run a war to be able to import my own module (who python thinks he is ????)... It is driving me crazy.
So for now the 'best' trick I have found, but clearly I am not satisfied with it is to put ligne like this on top of my file:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(file))))
I do not like it, first because when the directory is nested on several level the line is extraordinary long, then because my linter is always yelling at me because my import are not on top of my files.
So I was wondering, what am I missing ? Is there an information I missed ? What's your technique ?
Thank you !
Can't import my own modules in Python
Someone suggested it's similar to this answer but it is not.
First I do not want to use relative import.
Then the 'sys.path.append("..")' is not clean in my opinion, and my imports are still not on top of my files.
Basically let's say I have a structure like:
folder_a
----file_1
----file2
----folder_b
--------file_3
--------folder_c
-----------file_4
I am instanciating a class from file_1 in file_3,I have to do this:
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file)))))
from folder_a.file_1 import class_1
doing this obviously won't work:
sys.path.append("..")
from folder_a.file_1 import class_1
This is so not logic for me
If you don't want to use relative imports, and you don't want to mess with sys.path, the other option is to package your modules and install them using pip install.
I think that reading the import documentation instead of just trying to "make it work" will be beneficial. Python's documentation is really good. Focus for a while with a good cup of tea and read it :)

Python - Importing function from external file and global modules

In order to simplify my code, I have put various functions into external files with I load via:
from (external_file) import (function_name)
...which works fine.
My question though has to do with other modules, such as cv2 or numpy - do I need those listed in my external file (as well as my main file) or is there a way to just list them in my main file?
Each file you put Python code in is its own module. Each module has its own namespace. If some of your code (in any module) uses some library code, it will need some way to access the library from the namespace it is defined in.
Usually this means you need to import the library in each module it's being used from. Don't worry about duplication, modules are cached when they are first loaded, so additional imports from other modules will quickly find the existing module and just add a reference to it in their own namespaces.
Note that it's generally not a good idea to split up your code too much. There's certainly no need for every function or every class to have its own file. Instead, use modules to group related things together. If you have a couple of functions that interoperate a lot, put them in the same module.

Put imports at the top? Or where they get used? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python import coding style
When I write some code that requires an import, and the import is only introduced by the bit of code I'm currently writing, should I:
Stick the import at the top of the file where it is made clear that to make this module work it needs these imports, yet the import is detached from the usage and should the need be removed later the module may still import stuff it doesn't ever actually use, or
Keep the import with the code that uses it immediately thereafter so it is obvious what the import is used to do and whence it can be safely removed, but risk importing the same libs multiple times and make it hard to work out what libs are required to make the module work.
Best practice?
Put the import at the top? Or put it where it gets used?
Import_Statement_Overhead from the Python wiki states:
"import statements can be executed just about anywhere. It's often
useful to place them inside functions to restrict their visibility
and/or reduce initial startup time. Although Python's interpreter is
optimized to not import the same module multiple times, repeatedly
executing an import statement can seriously affect performance in some
circumstances."
I follow general stylistic conventions and put all of my import statements at the top of the program. PEP 8 states re imports:
"Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants."

Python Auto Importing [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Perl's AUTOLOAD in Python (getattr on a module)
I'm coming from a PHP background and attempting to learn Python, and I want to be sure to do things the "Python way" instead of how i've developed before.
My question comes from the fact in PHP5 you can set up your code so if you attempt to call a class that doesn't exist in the namespace, a function will run first that will load the class in and allow you to continue on as if it were already loaded. the advantages to this is classes weren't loaded unless they were called, and you didn't have to worry about loading classes before using them.
In python, there's alot of emphasis on the import statement, is it bad practice to attempt an auto importing trick with python, to alleviate the need for an import statement? I've found this module that offers auto importing, however I dont know if that's the best way of doing it, or if auto importing of modules is something that is recommended, thoughts?
Imports serve at least two other important purposes besides making the modules or contents of the modules available:
They serve as a sort of declaration of intent -- "this module uses services from this other module" or "this module uses services belonging to a certain class" -- e.g. if you are doing a security review for socket-handling code, you can begin by only looking at modules that import socket (or other networking-related modules)
Imports serve as a proxy for the complexity of a module. If you find yourself with dozens of lines of imports, it may be time to reconsider your separation of concerns within the module, or within your application as a whole. This is also a good reason to avoid "from foo import *"-type imports.
In Python, people usually avoid auto imports, just because it is not worth the effort. You may slightly remove startup costs, but otherwise, there is no (or should be no) significant effect. If you have modules that are expensive to import and do a lot of stuff that doesn't need to be done, rather rewrite the module than delay importing it.
That said, there is nothing inherently wrong with auto imports. Because of the proxy nature, there may be some pitfalls (e.g. when looking at a thing that has not been imported yet). Several auto importing libraries are floating around.
If you are learning Python and want to do things the Python way, then just import the modules. It's very unusual to find autoimports in Python code.
You could auto-import the modules, but the most I have ever needed to import was about 10, and that is after I tacked features on top of the original program. You won't be importing a lot, and the names are very easy to remember.

Categories