Passing args = (elements) is equivalent to args = elements, i.e. no tuple is created.

To pass a 1-element tuple, either do args = (elements,), or args = tuple([elements]).

Answer from shx2 on Stack Overflow
๐ŸŒ
SciPy
docs.scipy.org โ€บ doc โ€บ scipy โ€บ reference โ€บ optimize.html
Optimization and root finding (scipy.optimize) โ€” SciPy v1.17.0 Manual
It includes solvers for nonlinear problems (with support for both local and global optimization algorithms), linear programming, constrained and nonlinear least-squares, root finding, and curve fitting. Common functions and objects, shared across different solvers, are: The minimize_scalar function supports the following methods: ... Constraints are passed to minimize function as a single object or as a list of objects from the following classes:
Discussions

performance - How much slower python classes are compared to their equivalent functions? - Stack Overflow
Sure, code with classes might be a little slower through indirection. Maybe. That is what JIT compilation is for, right? I can never remember which versions of python do this and which don't, because: Performance doesn't matter. At least constant performance differences like this. Unless you are doing a hell of a lot of computations (you aren't!), you will spend more time developing/debugging/maintaining your code. Optimize ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Minimising an objective function which is a method of a class - Stack Overflow
I have a class XYZ() with methods build and Predict. I have another class BuildSurrogate() which has an attribute SurrogateClass pointing to an object of type class XYZ(). A method of SurrogateClas... More on stackoverflow.com
๐ŸŒ stackoverflow.com
June 10, 2016
python - How to use scipy's minimize within a class? - Stack Overflow
I'm new to python so this might be a stupid question, however I couldn't find an answer to this anywhere. I'm trying to find the optimal reaction for a player given the action of another player. The situation is your typical Bertrand price competition for those familiar economics. The code is as follows: import numpy as np from scipy.optimize import minimize class ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - class method as a model function for scipy.optimize.curve_fit - Stack Overflow
There is a statement in the manual of curve_fit that The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ PythonSpeed โ€บ PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
Certain optimizations amount to good programming style and so should be learned as you learn the language. An example would be moving the calculation of values that don't change within a loop, outside of the loop. ... Sorting lists of basic Python objects is generally pretty efficient.
Top answer
1 of 4
51

To answer the question: yes, it is likely to be a little slower, all else being equal. Some things that used to be variables (including functions) are now going to be object attributes, and self.foo is always going to be slightly slower than foo regardless of whether foo was a global or local originally. (Local variables are accessed by index, and globals by name, but an attribute lookup on an object is either a local or a global lookup, plus an additional lookup by name for the attribute, possibly in multiple places.) Calling a method is also slightly slower than calling a function -- not only is it slower to get the attribute, it is also slower to make the call, because a method is a wrapper object that calls the function you wrote, adding an extra function call overhead.

Will this be noticeable? Usually not. In rare cases it might be, say if you are accessing an object attribute a lot (thousands or millions of times) in a particular method. But in that case you can just assign self.foo to a local variable foo at the top of the method, and reference it by the local name throughout, to regain 99.44% of the local variable's performance advantage.

Beyond that there will be some overhead for allocating memory for instances that you probably didn't have before, but unless you are constantly creating and destroying instances, this is likely a one-time cost.

In short: there will be a likely-minor performance hit, and where the performance hit is more than minor, it is easy to mitigate. On the other hand, assuming your problem lends itself to an object-oriented solution, you could save hours in writing and maintaining the code. And saving time is likely why you're using a language like Python to begin with.

2 of 4
35

No.

In general you will not notice any difference in performance based on using classes or not. The different code structures implied may mean that one is faster than the other, but it's impossible to say which.

Always write code to be read, then if, and only if, it's not fast enough make it faster. Remember: Premature optimization is the root of all evil.

๐ŸŒ
Experfy
training.experfy.com โ€บ courses โ€บ object-oriented-python-performance-optimization
Object Oriented Python/Performance Optimization | Object Oriented Python - Python Performance Course | Experfy
Students that would like to learn ... Python applications for the first time may also benefit. This course dives into utilizing Python for creating advanced class objects and optimizing them for production value....
Rating: 5 โ€‹ - โ€‹ 4 votes
๐ŸŒ
Stephen Appiah
blog.stevenwithph.com โ€บ optimizing-python-classes
Optimizing Python Classes | cached_property, staticmethod and slots
May 6, 2023 - Let's first illustrate when and how to use static methods in Python. ... class Weather: def __init__(self, temperature, humidity): self.temperature = temperature self.humidity = humidity def is_weather_good(self, temperature, humidity): if temperature > 20 and humidity < 80: return True else: return False
๐ŸŒ
Real Python
realpython.com โ€บ lessons โ€บ optimization-data-classes
Optimization of Data Classes (Video) โ€“ Real Python
00:59 In essence, slots are defined using the .__slots__ to list the variables on a class. Variables or attributes not present in the .__slots__ list may not be defined. Furthermore, a slots class may not have default values. 01:16 The benefit of adding such restrictions is that optimizations can be performed.
Published ย  September 14, 2021
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ optimization-in-python
Optimization in Python: Techniques, Packages, and Best Practices | DataCamp
August 31, 2024 - Learn about memory management in Python with advanced techniques for coding memory-efficient classes. Explore practical exercises for optimal performance.
Find elsewhere
Top answer
1 of 1
1

Starting with an example for minimize documentation:

In [183]: x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
In [185]: optimize.minimize(optimize.rosen, x0, method='Nelder-Mead', tol=1e-6)
Out[185]: 
 final_simplex: (array([[ 1.00000002,  1.00000002,  1.00000007,  1.00000015,  1.00000028],
...
             x: array([ 1.00000002,  1.00000002,  1.00000007,  1.00000015,  1.00000028])

Define a callable class that does the same thing:

In [191]: class Class1(object):
    def __init__(self):
        pass
    def __call__(self,args):
        return optimize.rosen(args)
In [190]: optimize.minimize(Class1(), x0, method='Nelder-Mead', tol=1e-6)

A Class1 object is callable, so I can use it exactly as though I had defined a rosen method

In [191]: Class1()(x0)
Out[191]: 848.22000000000003

I could have defined it this way:

In [192]: class Class2(object):
    def rosen(self,args):
        return optimize.rosen(args)   

In [193]: optimize.minimize(Class2().rosen, x0, method='Nelder-Mead', tol=1e-6)

In [194]: Class2().rosen(x0)
Out[194]: 848.22000000000003

Adding in class layer shouldn't make a difference, just so long as the first argument to minimize is a function that returns a value when called with x0.

In your case you just need to define:

class XYZ(object):
    def predict(self, args):
        return optimize.rosen(args)

class BuildSurrogate(object):
    def __init__(self):
        self.surrogateObj = XYZ()
    def minima(self,x0):
        return optimize.minimize(self.surrogateObj.predict, x0, method='Nelder-Mead', tol=1e-6)

And use:

BuildSurrogate().minima(x0)

Or something comparable.

I could have also defined self.SurrogateClass=XYZ and called self.SurrogateClass().predict. As long as predict is a method of the XYZ class I have to create an XYZ() object before using it.

๐ŸŒ
Python
python.org โ€บ doc โ€บ essays โ€บ list2str
Python Patterns - An Optimization Anecdote | Python.org
This is because local variable lookups are much faster than global or built-in variable lookups: the Python "compiler" optimizes most function bodies so that for local variables, no dictionary lookup is necessary, but a simple array indexing operation is sufficient.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ __slots__
__slots__ for optimizing classes - Python Morsels
November 4, 2025 - Let's talk about how to optimize the memory usage and the attribute lookup time of our Python classes.
๐ŸŒ
Readthedocs
python-mip.readthedocs.io โ€บ en โ€บ latest โ€บ classes.html
Classes โ€” Python-MIP documentation
One or more variables that appear in the objective function are not included in binding constraints and the optimal objective value is infinity. ... An enumeration. ... Default search emphasis, try to balance between improving the dual bound and producing integer feasible solutions. ... More aggressive search for feasible solutions. ... Focuses more on producing improved dual bounds even if the production of integer feasible solutions is delayed. ... Different methods to solve the linear programming problem. ... Class to store the improvement of lower and upper bounds over time during the search.
๐ŸŒ
Google
developers.google.com โ€บ or-tools โ€บ get started with or-tools for python
Get Started with OR-Tools for Python | Google for Developers
Users need to identify their problem type and choose the appropriate solver to find the optimal solution. Python programs using OR-Tools typically involve importing libraries, declaring the solver, defining variables, constraints, and the objective ...
๐ŸŒ
SciPy
docs.scipy.org โ€บ doc โ€บ scipy โ€บ tutorial โ€บ optimize.html
Optimization (scipy.optimize) โ€” SciPy v1.17.0 Manual
Such a problem falls within the larger class of mixed integer linear programs (MILPs), which we we can solve with milp. In our example, there are 8 items to choose from, and the size and value of each is specified as follows. >>> import numpy as np >>> from scipy import optimize >>> sizes = ...
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ how to optimize python code?
r/Python on Reddit: How to optimize python code?
January 28, 2022 -

Hi Pythonistas,

I'm interested in learning what optimization techniques you know for python code. I know its a general statement, but I'm interested in really pushing execution to the maximum.

I use the following -

  1. I declare __slots__ in custom classes

  2. I use typing blocks for typing imports

  3. I use builtins when possible

  4. I try to reduce function calls

  5. I use set lookups wherever possible

  6. I prefer iteration to recursion

Edit: I am using a profiler, and benchmarks. I'm working on a library - an ASGI Api framework. The code is async. Its not darascience. Its neither compatible with pypy, nor with numba..

What else?

๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ write-memory-efficient-classes-in-python
How to Write Memory-Efficient Classes in Python | DataCamp
July 4, 2024 - Tuples generally use less memory than lists because they have a fixed size and cannot be altered once created, allowing Pythonโ€™s internal mechanisms to optimize their storage in memory. For classes designed to handle data that does not need modification post-creation, tuples are an excellent choice.
๐ŸŒ
Stackify
stackify.com โ€บ how-to-optimize-python-code
Best Method of Python Code Optimization - Stackify - Ivanov
September 16, 2023 - Itโ€™s crucial when it comes to processing a large number of operations or data while performing a task. Thus, replacing and optimizing some inefficient code blocks and features can work wonders: ... Save a lot of computational power, and so on. There are certain scenarios where Python can lead to performance issues.
๐ŸŒ
Duke University
people.duke.edu โ€บ ~ccc14 โ€บ sta-663 โ€บ MakingCodeFast.html
Code Optimization โ€” Computational Statistics in Python 0.1 documentation
Profiling means to time your code so as to identify bottelnecks. If one function is taking up 99% of the time in your program, it is sensiblt to focus on optimizign that function first.